Follow

When initializing an array, is

`arr = []`

just syntactic sugar for

`arr = Array.new([])`

? Or am I not thinking about this correctly? The docs aren't clear on this point, at least to me.

@adamlombard I would not call it syntactic sugar...

When ruby interpreter read this statement:

arr = []

This method is executed

rb_ary_s_create(int argc, VALUE *argv, VALUE klass)

github.com/ruby/ruby/blob/4020

and jruby

github.com/jruby/jruby/blob/d3

OTOH, when found this:

arr = Array.new []

This method is executed:
rb_ary_initialize(int argc, VALUE *argv, VALUE ary)

github.com/ruby/ruby/blob/4020

Basically the interpreter/compiler would execute two different methods, one more expensive that the other

@adamlombard but also...

This:

arr = []
# => []

It is syntactic sugar for:

arr = Array.[]
# => []

But is *not* syntactic sugar for this:

arr = Array []
# => []

@esparta @presidentbeef

This confirms my confusion, but doesn't clear it up. :)

Most entry-level Ruby stuff I've encountered treats `arr = []` and `arr = Array.new` as if they are completely interchangeable. Often it's pitched as "Ruby gives you different ways to do things!" But, as @esparta pointed out, that's not completely true here --they're actually two different methods.

My question is -- why? My C is weak, so I'm not understanding the difference between the two.

@adamlombard @esparta `[]` is not a method call, it's an array literal that can be directly translated into an Array object by the interpreter. `Array.new` is a method call. You can see the difference if you override Array's initialize method:

2.3.0 :001 > class Array
2.3.0 :002?> def initialize *args
2.3.0 :003?> puts "hi"
2.3.0 :004?> super
2.3.0 :005?> end
2.3.0 :006?> end
=> :initialize
2.3.0 :007 > []
=> []
2.3.0 :008 > Array.new
hi
=> []

A beginner shouldn't care IMO

@adamlombard @esparta Or compare

puts RubyVM::InstructionSequence.compile("[]").disasm

to

puts RubyVM::InstructionSequence.compile("Array.new").disasm

@presidentbeef @adamlombard
I'm agree, maybe my wording was not correct. I didn't mean to say [] is a method call, I meant to say that different methods are executed (and it's independent of the implementation language that can be C, or Java or .NET), that's verified on the `disasm` proof.

And also agree, beginners shouldn't care. I realized that's was a beginner Q.

@adamlombard `Array.new([])` would create a copy of the array argument.

Sign in to participate in the conversation
Ruby.social

A Mastodon instance for Rubyists & friends