all the time i thought [] would be a shortcut for the corresponding
class method of the class Array, but after
def Array.[](*args)
puts "blah"
end
i still get
a= [1, 2, 3]
=> [1, 2, 3]
and on the other hand
a= Array[1, 2, 3] # or a= Array.[](1, 2, 3)
blah
=> nil
so what is the exact cause of the difference?
can I somehow redefine the 'global' []
You defined Array#[] and nothing else.
> can I somehow redefine the 'global' []
No, you can't. That's special syntax - it's a constructor like "foo".
Kind regards
robert
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
no. [1, 2, 3] is an array literal and part of the syntax. It does not invoke a method. Array[...] is, as you point out in the comment, a method invocation to Array::[](*items).
I don't think so. Array() is a method of the Kernel module. So, I think,
`Array[1,2,3]` equals `Array( [1,2,3] )`.
--
Posted via http://www.ruby-forum.com/.
Array([1,2,3]) calls the Array kernel method on the Array created by [1,
2, 3]. Array[1, 2, 3] calls the [] method on the Array class. Very
different.
ffffff passes the Array created by [1, 2, 3] to the Array method of
Kernel.
Right. Thanks for correcting me.
> Ryan Davis wrote:
>> Array[...] is, as you point out in the comment, a
>> method invocation to Array::[](*items).
>
> I don't think so. Array() is a method of the Kernel module. So, I think,
> `Array[1,2,3]` equals `Array( [1,2,3] )`.
If there is one thing I know about ruby, it's the damn grammar. :P
% echo "Array[1,2,3]" | parse_tree_show
s(:call,
s(:const, :Array),
:[],
s(:arglist, s(:lit, 1), s(:lit, 2), s(:lit, 3)))
Ruby's syntax allows you to not use "." for [] and []=, which is why we can do things like my_hash[key] or my_array[42] = 24 instead of my_hash.[](key) or my_array.[]=(42, 24). Classes are objects too and subject to the same syntactical rules.
echo "[1,2,3]" | parse_tree_show
s(:array, s(:lit, 1), s(:lit, 2), s(:lit, 3))
echo "Array[1,2,3]" | parse_tree_show
s(:call, s(:const, :Array), :[], s(:array, s(:lit, 1), s(:lit, 2),
s(:lit, 3)))
echo "Array.[](1,2,3)" | parse_tree_show
s(:call, s(:const, :Array), :[], s(:array, s(:lit, 1), s(:lit, 2),
s(:lit, 3)))
...
but back to my original question: it seems to me to be a violation of
the PLS that
[] ist not somehow tied to Array#[]
same should apply to {} and Hash#[] etc.
what are the real reasons for a separation of this concepts?