Search code examples
rubyblock

Weird imoperfection in Ruby blocks


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.


Solution

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