Why isn't the Ruby 1.9 lambda call possible wi

2019-04-03 20:39发布

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?

2条回答
贪生不怕死
2楼-- · 2019-04-03 21:19

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

查看更多
再贱就再见
3楼-- · 2019-04-03 21:33

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.

查看更多
登录 后发表回答