Ruby array creation, Array.new vs []
[]
is a shortcut to the Array class's singleton method []
which in turn creates a new Array in just the same way as Array.new
, so you could probably say 'they are the same' without worrying too much.
Note that each call to []
in irb creates a new Array:
>> [].object_id
=> 2148067340
>> [].object_id
=> 2149414040
From Ruby's C code:
rb_define_singleton_method(rb_cArray, "[]", rb_ary_s_create, -1);
Those two statements are functionally identical. Array.new
however can take arguments and a block:
Array.new # => []
Array.new(2) # => [nil,nil]
Array.new(5,"A") # =>["A","A","A","A","A"]
a = Array.new(2,Hash.new)
a[0]['cat'] = 'feline'
a # => [{"cat"=>"feline"},{"cat"=>"feline"}]
a[1]['cat'] = 'Felix'
a # => [{"cat"=>"Felix"},{"cat"=>"Felix"}]
a = Array.new(2){Hash.new} # Multiple instances
a[0]['cat'] = 'feline'
a # =>[{"cat"=>"feline"},{}]
squares = Array.new(5){|i|i*i}
squares # => [0,1,4,9,16]
copy = Array.new(squares) # initialized by copying
squares[5] = 25
squares # => [0,1,4,9,16,25]
copy # => [0,1,4,9,16]
Note: the above examples taken from Programming Ruby 1.9