Array.new(array)
Array.new(size) {|index| block }
Returns a new array.
In the first form, if no arguments are sent, the new array will be empty.
When a size
and an optional obj
are sent, an
array is created with size
copies of obj
. Take
notice that all elements will reference the same object obj
.
The second form creates a copy of the array passed as a parameter (the array is generated by calling #to_ary on the parameter).
first_array = ["Matz", "Guido"] second_array = Array.new(first_array) #=> ["Matz", "Guido"] first_array.equal? second_array #=> false
In the last form, an array of the given size is created. Each element in this array is created by passing the element's index to the given block and storing the return value.
Array.new(3){ |index| index ** 2 } # => [0, 1, 4]
Common gotchas
When sending the second parameter, the same object will be used as the value for all the array elements:
a = Array.new(2, Hash.new) # => [{}, {}] a[0]['cat'] = 'feline' a # => [{"cat"=>"feline"}, {"cat"=>"feline"}] a[1]['cat'] = 'Felix' a # => [{"cat"=>"Felix"}, {"cat"=>"Felix"}]
Since all the Array elements store the same hash, changes to one of them will affect them all.
If multiple copies are what you want, you should use the block version which uses the result of that block each time an element of the array needs to be initialized:
a = Array.new(2) { Hash.new } a[0]['cat'] = 'feline' a # => [{"cat"=>"feline"}, {}]
Please login to continue.