max
max

Reputation: 102368

Is the Ruby literal array syntax a method call?

Is the Ruby literal array syntax:

[1,2,3]

A shortcut to:

Array[1,2,3]

And thus a constructor method call? Or does it do some other low level magic? I was looking specifically at how you can use keywords:

[1,2,3, foo: 'bar'] 

And it has the same effects as a method call.

Upvotes: 1

Views: 89

Answers (1)

sepp2k
sepp2k

Reputation: 370435

The behaviour of [1, 2, 3] is built-in - it is not a shortcut for Array[1, 2, 3]. You can see this be redefining Array[]:

def Array.[](*args)
  puts "Array[] called with arguments #{args}"
end

p [1, a: "b"]      # Will print '[1, {:a=>"b"}]'
p Array[1, a: "b"] # Will print 'Array[] called with arguments [1, {:a=>"b"}]' followed by "nil"

The way that foo: "bar" is handled is simply a consequence of the rule that hash literals can be written without {} when used as the last argument in a method call or array literal. It's only interpreted as a keyword argument when calling a method that's defined to take keyword arguments, otherwise it's treated as a hash.

Upvotes: 4

Related Questions