What\'s the difference between these two statements? I use them in my rails app and to me it looks like they do the same thing
array_a = Array.new
array_b =
Such as Hash.new
vs {}
. They are the same. Include speed.
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
As others have already answered you
Those two statements are functionally identical
But there are guidelines to orient when you should use each one (so your code is easier to read). The reason behind that is:
Programs must be written for people to read, and only incidentally for machines to execute.
from: https://github.com/rubocop-hq/ruby-style-guide#literal-array-hash
Prefer literal array and hash creation notation (unless you need to pass parameters to their constructors, that is).
So if you are creating an empty array []
is the best option, but if you need to create your array with a set of N nil objects, than Array.new(N)
is what you should write.
[]
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);
There is fundamentally no difference