38

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 = []
1
  • 1
    To clear/reset array without creating a new object, use array.clear to achieve #=> [ ] Commented Mar 28, 2015 at 10:53

5 Answers 5

78

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

Sign up to request clarification or add additional context in comments.

3 Comments

Array.new(count, object) producing an array of the same object is a gotcha that means I avoid using that approach.
@Andrew: not exactly in line with the "principle of least surprise", is it?
lucky that i found your answer within a minute of my doubt.
10

[] 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);

Comments

2

Such as Hash.new vs {}. They are the same. Include speed.

Comments

2

There is no difference, but...

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.

Comments

1

There is fundamentally no difference

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.