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?
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!"