0

(至少某种)Ruby 代码在方法的默认值规范中被接受和评估。在下面,"foo" * 3评估:

def bar baz = "foo" * 3; baz end
bar # => "foofoofoo"

def bar baz: "foo" * 3; baz end
bar # => "foofoofoo"

但是,当我尝试在默认值描述中的某个范围内评估局部变量/方法时,如下所示,局部变量/方法是在词法范围下评估的:

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
  • 为什么foo上面没有在MAIN范围内评估而在词法范围内评估?
  • 这似乎对可以在默认值描述中评估的 Ruby 表达式有一些限制。究竟可以放什么?
4

1 回答 1

1

foo is local variable for main. Your attempt to access local variable from outside might be shorten to:

▶ MAIN = TOPLEVEL_BINDING.eval('self')
▶ foo = 3
▶ MAIN.foo
#⇒ NoMethodError: undefined method `foo' for main:Object

The analogue of this code in less tangled manner is:

class A
  foo = 5
end

class B
  def a_foo
    A.new.foo
  end
end

▶ B.new.a_foo
#⇒ NoMethodError: undefined method `foo' for #<A:0x00000002293bd0>

If you want to provide access from the universe to your local variable you are to implement getter:

def MAIN.foo ; 5 ; end
def bar baz = MAIN.instance_eval{foo}; baz; end

▶ bar
#⇒ 5

Hope it helps.

于 2014-12-27T06:22:39.327 回答