Why isn't the Ruby 1.9 lambda call possible without the dot in front of the parentheses ?
Asked Answered
D

2

19

I checked out the latest Ruby version, to play a bit with the latest changes. The first thing I tried to do was call a Ruby lambda/block/proc just like you'd do with a Python callable.

a = lambda {|x| puts x}
a.call(4) # works, and prints 4
a[4] # works and prints 4
a.(4) # same
a(4) # undefined method 'a' for main:Object

Why isn't the last call possible? Will it ever be?

Down answered 6/11, 2009 at 10:54 Comment(0)
N
10

AFAIK it's because ruby doesn't let you define the () method for an object. The reason it doesn't let you define the () method is probably due to the fact that parentheses are optional in method calls.

And for what it's worth, here's a hack to let you invoke lambdas using () http://github.com/coderrr/parenthesis_hacks/blob/master/lib/lambda.rb

Nones answered 19/1, 2010 at 22:25 Comment(3)
can you please explain the lambda script a bit?Down
ok, when you try to invoke a method named blah() and method_missing is triggered it checks to see whether a lambda called blah is defined in the appropriate context. If such a lambda is defined then it just invokes the lambda using the usual blah.call syntax, it also passes along any parameters that were givenNones
I think this is an awesome hack. Thank you.Down
C
6

Ruby is basically 100% object-oriented, but sometimes it tries to hide this fact for... convenience? Familiarity?

Basically functions defined "at the top level" are really defined as methods on a global object. To make that work, a call without a specifier is really converted to calling a method with that name on said global object. This style makes things look more script-y. Ruby is trying to do that with your last example.

The first two examples parse fine because Ruby knows you are trying to access the methods of the proc object--remember even [] is just a method you can define. The one with the explicit dot also works because the dot means "send this message to this object" (in this case, a).

I know that doesn't "solve" anything, but I hope it helps a bit.

Cota answered 3/12, 2009 at 23:59 Comment(2)
The fact that ruby is OOP doesn't explain why you cannot use () to invoke a lambda. Many languages let you define a () method for your objects. The question really is why doesn't ruby let you define a () operator?Nones
(Just now saw this comment...) Good question. Maybe it has something to do with how you can omit parentheses in certain situations; would be weird to have an implicit overloaded operator call.Cota

© 2022 - 2024 — McMap. All rights reserved.