Reputation: 18159
class Test
def << (*args)
print "I got #{args.size} parameters.\n"
end
end
This works:
t = Test.new
t << 5
This doesn't work:
t = Test.new
t << 5,10
But this DOES work:
t = Test.new
t.<< 5,10
Why doesn't the second case work? Shouldn't it be equivalent to the third case?
Upvotes: 2
Views: 294
Reputation: 118299
It works :-
class Test
def << (*args)
print "I got #{args.size} parameters.\n"
end
end
t = Test.new
t << [5,10]
# >> I got 1 parameters.
t << (5..10)
# >> I got 1 parameters.
Why doesn't the second case work?
You have to pass it then in an array format(means you need to pass only one object as an argument). Your second one didn't work due to operator precedence
.<<
has higher precedence then ,
. So your expression t << 5,10
becomes as (t << 5),10
. That is why you got the error.
Upvotes: 4