Search code examples
rubyinterpreteroperator-precedence

Why does Ruby raise error for last undefined variable on line?


Assuming that foo, bar, and baz have not been defined, the line

foo bar baz

raises this error:

NameError (undefined local variable or method `baz' for main:Object)

In REPLs for Python, PHP, and Javascript the first issue in foo(bar(baz)) is that foo is not defined. Why does Ruby complain about baz first?


Solution

  • Ruby allows the first method invoked (baz) to dynamically define the other two methods. It doesn't attempt to resolve foo or bar as method invocations until the actual method invocation happens, and it never reaches that method invocation as baz first causes an error.

    If baz dynamically defines the methods foo and bar, there is no problem:

    def baz
      define_method(:foo) { |x| "foo #{x}" }
      define_method(:bar) { |x| "bar #{x}" }
      "baz!"
    end
    
    foo bar baz # => "foo bar baz!"