如果定义了Ruby常量,为什么它不是由常量()列出的?

时间:2013-12-06 13:26:00

标签: ruby class constants

当您使用const_defined?()检查它们时,类名似乎会出现,但是当您尝试使用常量()列出它们时却不会出现。由于我有兴趣列出任何已定义的类名,我只是想弄清楚发生了什么。例如:

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
[]

方法不应该同意吗?我错过了什么?

1 个答案:

答案 0 :(得分:2)

您正在使用的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]