根据Ruby的const_get文档,该方法返回一个常量的值。
因此,要重现以下行为:
我写了这段代码:
因此,要重现以下行为:
module A
FOO = 42
module B
def self.call
FOO
end
end
end
A::B.call # => 42
我写了这段代码:
A = Module.new
A.const_set(:FOO, 42)
A.const_set(:B, Module.new do
def self.call
const_get(:FOO)
end
end)
但是当我调用这个方法时,我遇到了一个 NameError
异常:
A::B.call # => exception
# NameError (uninitialized constant A::B::FOO)
# Did you mean? A::FOO
看起来FOO
和const_get(:FOO)
并不完全相同。
是否有另一种递归查找父模块中FOO
常量的方法?
编辑:
我直接使用const_get
也遇到了这个问题:
module A
FOO = 42
module B
def self.a_method
const_get(:FOO)
end
end
end
A::B.a_method # => exception
# NameError (uninitialized constant A::B::FOO)
# Did you mean? A::FOO
call
)可能会令人困惑,甚至有问题。 - Cary Swovelandmodule A
内部定义module B
与直接定义module A::B
实际上是不同的。嵌套的方式意味着在另一种方式下不存在的搜索范围。 - tadmanconst_get(:FOO)
替换了FOO
。但它不再起作用了。所以我认为问题来自于const_get
方法。 - Zag zag..