为什么 Ruby 1.9 的 lambda 调用不能在括号前面没有点?
我查看了最新的 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
为什么最后一个电话打不通?会是这样吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
AFAIK 这是因为 ruby 不允许您为对象定义
()
方法。它不允许您定义()
方法的原因可能是因为括号在方法调用中是可选的。无论如何,这里有一个技巧,可以让您使用
()
调用 lambdaAFAIK 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.rbRuby 基本上是 100% 面向对象的,但有时它会为了……方便而试图隐藏这一事实?熟悉吗?
基本上,“顶层”定义的函数实际上被定义为全局对象上的方法。为了实现这一点,不带说明符的调用实际上会转换为在所述全局对象上调用具有该名称的方法。这种风格让事情看起来更加脚本化。 Ruby 正在尝试用你的最后一个例子来做到这一点。
前两个示例解析得很好,因为 Ruby 知道您正在尝试访问 proc 对象的方法——记住,即使
[]
也只是您可以定义的方法。带有显式点的也可以工作,因为点的意思是“将此消息发送到此对象”(在本例中为a
)。我知道这并不能“解决”任何问题,但我希望它能有所帮助。
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.