Weird imoperfection in Ruby blocks [duplicate]

最后都变了- 提交于 2019-12-17 16:43:45

问题


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.


回答1:


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).

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.



来源:https://stackoverflow.com/questions/7620804/weird-imoperfection-in-ruby-blocks

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!