我查看了最新的 Ruby 版本,以了解最新的变化。我尝试做的第一件事是调用 Ruby lambda/block/proc,就像使用 Python 可调用对象一样。
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
为什么最后一个电话不可能?会是吗?
我查看了最新的 Ruby 版本,以了解最新的变化。我尝试做的第一件事是调用 Ruby lambda/block/proc,就像使用 Python 可调用对象一样。
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
为什么最后一个电话不可能?会是吗?
AFAIK 这是因为 ruby 不允许您定义()
对象的方法。它不允许您定义()
方法的原因可能是因为括号在方法调用中是可选的。
对于它的价值,这里有一个 hack 让你使用()
http://github.com/coderrr/parenthesis_hacks/blob/master/lib/lambda.rb调用 lambdas
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.