【问题标题】:If a Ruby constant is defined, why isn't it listed by constants()?如果定义了一个 Ruby 常量,为什么它没有被 constants() 列出呢?
【发布时间】:2013-12-06 13:25:59
【问题描述】:

当您使用 const_defined?() 检查类名时似乎会显示它们,但当您尝试使用 constants() 列出它们时不会显示。因为我有兴趣列出任何已定义的类名,所以我只是想弄清楚发生了什么。示例:

class MyClass
  def self.examine_constants
    puts self.name
    puts const_defined? self.name
    puts constants.inspect
  end
end

MyClass.examine_constants

在 Ruby 2.0.0p195 下,该代码给出以下结果:

MyClass
true
[]

方法不应该一致吗?请问我错过了什么?

【问题讨论】:

    标签: ruby class constants


    【解决方案1】:

    您使用的Module#constant 方法返回当前范围内的所有常量。您可能想要使用的是类方法Module.constant,它返回所有顶级常量。例如:

    class MyClass
      def self.examine_constants
        puts self.name
        puts const_defined? self.name
        puts Module.constants.inspect
      end
    end
    
    MyClass.examine_constants
    

    回复:

    MyClass
    true
    [...lots of other constants, :MyClass]
    

    【讨论】:

    • 太好了。按照您的建议,我可以查看所有类定义等。只是想完全理解这一点:当我在没有接收器的情况下调用 constants() 时,就像在我的原始代码中一样,是不同的方法还是相同的方法以不同的方式调用,从而产生不同的结果?
    • 它们是不同的方法。您调用的Module#constants 将成为您的类的实例方法。另一个Module.constants 是类方法(在这种情况下是模块方法)。供参考:ruby-doc.org/core-2.0.0/Module.html#method-c-constants
    • 优秀。来自该链接:“这...包括在全局范围内定义的所有模块和类的名称。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 2013-11-05
    • 2015-02-25
    • 2020-07-04
    • 1970-01-01
    • 2020-02-25
    • 1970-01-01
    相关资源
    最近更新 更多