Arrays

Array literals

Square brackets build an array, with elements separated by commas. Elements may mix types, because an array holds references to objects, not fixed slots. The factory method Array.new builds a sized array filled with one default value.

nums = [1, 2, 3] mixed = ["Ada", 36, true] zeros = Array.new(3, 0) puts zeros.length

3

The last line prints 3, because zeros holds three copies of 0.

Read and write by index

Read an element with brackets and its position, starting at 0 for the first element. A negative index counts back from the end, so -1 is the last element. Reading a missing position returns nil, while assigning to a position replaces the value there.

names = ["Ada", "Bob", "Lin"] puts names[0] puts names[-1] names[1] = "Boris" puts names[1]

Ada
Lin
Boris

Push pop shift

The method push appends to the end, pop removes the last element and returns it, and shift removes the first element and returns it. The method length, with its alias size, tells how many elements are stored.

stack = [1, 2] stack.push(3) puts stack.length last = stack.pop puts last puts stack.length

3
3
2

Iterate with each

The method each hands every element to the block in order. When the position matters as well, each_with_index yields the element together with its index, starting at 0.

names = ["Ada", "Bob", "Lin"] names.each do |name| puts name end names.each_with_index do |name, i| puts "#{i}: #{name}" end

Ada
Bob
Lin
0: Ada
1: Bob
2: Lin

Next: Hashes

Article author: Arthur Isaev

Banner image