(At least some kind of) Ruby code is accepted and evaluated within the default value specification of a method. In below, "foo" * 3
is evaluated:
def bar baz = "foo" * 3; baz end
bar # => "foofoofoo"
def bar baz: "foo" * 3; baz end
bar # => "foofoofoo"
However, when I try to evaluate a local variable/method under a certain scope in the default value description as follows, the local variable/method is evaluated under lexical scope:
MAIN = TOPLEVEL_BINDING.eval('self')
foo = 3
def bar baz = MAIN.instance_eval{foo}; end
bar # => undefined local variable or method `foo' for main:Object
def bar baz: MAIN.instance_eval{foo}; end
bar # => undefined local variable or method `foo' for main:Object
- Why is
foo
above not evaluated withinMAIN
scope and is evaluated in lexical scope? - This seems there is some limitation to what Ruby expressions can be evaluated in the default value description. What exactly can be put there?