Ruby 如何使模常数在特征类中也可见?

Ruby 如何使模常数在特征类中也可见?,ruby,metaprogramming,eigenclass,Ruby,Metaprogramming,Eigenclass,我创建了一个模块,其中包含一个常量名称和一个方法hello。如果一个类包含该模块,那么这两个定义应该在不同的范围内可见 module A NAME = 'Otto' def self.included(base) base.extend(ClassMethods) end def hello(name = 'world') self.class.hello(name) end module ClassMethods def hello(name

我创建了一个模块,其中包含一个常量
名称
和一个方法
hello
。如果一个类包含该模块,那么这两个定义应该在不同的范围内可见

module A
  NAME = 'Otto'
  def self.included(base)
    base.extend(ClassMethods)
  end

  def hello(name = 'world')
    self.class.hello(name)
  end

  module ClassMethods
    def hello(name = 'world')
      "Hello #{name}!"
    end
  end
end

class B
  include A

  def instance_scope
    p [__method__, hello(NAME)]
  end

  def self.class_scope
    p [__method__, hello(NAME)]
  end

  class << self
    def eigen_scope
      p [__method__, hello(NAME)]
    end
  end
end

B.new.instance_scope
B.class_scope
B.eigen_scope

#=> script.rb:34:in `eigen_scope': uninitialized constant Class::NAME (NameError)
    from script.rb:41
模块A
NAME='Otto'
def自带(基本)
扩展(类方法)
结束
def hello(名称='world')
self.class.hello(姓名)
结束
模块类方法
def hello(名称='world')
“你好{name}!”
结束
结束
结束
B类
包括
def实例_范围
p[\uuuuu方法,你好(姓名)]
结束
def自我类_范围
p[\uuuuu方法,你好(姓名)]
结束
class script.rb:34:in`eigen_scope':未初始化的常量类::名称(NameError)
来自script.rb:41
但该常数在特征类的实例方法范围内不可见,
类解决方案

谢谢你的解释。有没有办法调整模块,使
hello\u name(name)
也能在本征类中工作?对不起,我不明白这个问题。你知道为什么常量查找在这种情况下工作得如此奇怪吗?在class_范围内,它工作得很好,但是
self
在这两种情况下都是一样的吗?谢谢你提出的有趣的问题。我学到了一些新东西@埃里克·杜米尼一点也不!你的解释很有用。
class << self
  def eigen_scope
    p [__method__, hello(self::NAME)]
    #=> [:eigen_scope, "Hello Otto!"]
  end
end
module A
  module ClassMethods
    NAME = 'Bob'
  end
end