Ruby块中的怪异功能不足 [英] Weird imoperfection in Ruby blocks
问题描述
可能重复:
有什么区别或价值Ruby中有哪些块编码样式?
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
}
为什么?
解释器似乎很困惑,并认为{...}是一个哈希.
It seems like the interpreter is confused and thinks that the { ... } is a hash.
当翻译无法理解实际有效的代码时,我总是会生气.它类似于具有许多此类问题的PHP.
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.
推荐答案
它不认为它是哈希,而是一个优先问题. {}
的绑定比do end
紧密,因此method :argument { other_method }
解析为method(:argument {other_method})
,在语法上无效(但是如果不是符号,则参数将是另一个方法调用).
It doesn't think it's a hash - it's a precedence issue. {}
binds tighter than do end
, so method :argument { other_method }
is parsed as method(:argument {other_method})
, which is not syntactically valid (but it would be if instead of a symbol the argument would be another method call).
如果添加括号(method(:argument) { other_method }
),它将可以正常工作.
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.
这篇关于Ruby块中的怪异功能不足的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!