Ruby 块中奇怪的不完美之处
# This works
method :argument do
other_method
end
# This does not
method :argument {
other_method
}
为什么?
解释器似乎很困惑,并认为 { ... } 是一个散列。
当解释器无法理解实际有效的代码时,我总是很生气。它与 PHP 类似,也有很多此类问题。
Possible Duplicate:
What is the difference or value of these block coding styles in Ruby?
# This works
method :argument do
other_method
end
# This does not
method :argument {
other_method
}
Why?
It seems like the interpreter is confused and thinks that the { ... } is a hash.
I always get angry when an interpreter can't understand a code that is actually valid. It resembles PHP that had many problems of this kind.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它不认为这是一个哈希 - 这是一个优先级问题。
{}
绑定比do end
更紧密,因此method :argument { other_method }
被解析为method(:argument {other_method})
,这在语法上是无效的(但如果参数不是符号而是另一个方法调用,那就是有效的)。如果添加括号 (
method(:argument) { other_method }
),它将正常工作。不,该代码实际上并不有效。如果是的话,那就行了。
It doesn't think it's a hash - it's a precedence issue.
{}
binds tighter thando end
, somethod :argument { other_method }
is parsed asmethod(:argument {other_method})
, which is not syntactically valid (but it would be if instead of a symbol the argument would be another method call).If you add parentheses (
method(:argument) { other_method }
), it will work fine.And no, the code is not actually valid. If it were, it would work.