new(...) public

Returns a new array. In the first form, the new array is empty. In the second it is created with size copies of obj (that is, size references to the same obj). The third form creates a copy of the array passed as a parameter (the array is generated by calling to_ary on the parameter). In the last form, an array of the given size is created. Each element in this array is calculated by passing the element’s index to the given block and storing the return value.

Array.new
Array.new(2)
Array.new(5, "A")

# only one copy of the object is created
a = Array.new(2, Hash.new)
a[0]['cat'] = 'feline'
a
a[1]['cat'] = 'Felix'
a

# here multiple copies are created
a = Array.new(2) { Hash.new }
a[0]['cat'] = 'feline'
a

squares = Array.new(5) {|i| i*i}
squares

copy = Array.new(squares)
Show source
Register or log in to add new notes.