仅迭代 public Ruby 个常量

Iterate over only public Ruby constants

从 Ruby 2.0 左右开始,可以使用 private_constant 将常量设为私有,如果直接在声明模块之外使用该常量会导致错误。

但是,constants and const_defined? still return private constants, and const_get 允许访问它们。有没有办法以编程方式识别私有常量并在 运行 时间将它们过滤掉?

(注意:What does Module.private_constant do? Is there a way to list only private constants? 及其答案并未专门针对这种情况,而是相反(如何仅列出 private 常量)。)


更新: 看起来好像在 Ruby 1.9 和 2.0 中,constants 只包含 public 常量。从 2.1 开始,无参数 constants 仍然只包含 public 常量,但是将 inherit 设置为 falseconstants(false) (即,仅列出定义在这个模块,不在它的祖先模块中)有暴露私有常量的副作用。

您可以通过以下方式识别常量:

class A
  C = "value"
  private_constant :C
  C2 = "value2"
end

A.constants #public constants
#=> [:C2]
A.constants(false) #public & private constants
#=> [:C, :C2]
A.constants(false) - A.constants #private constants
#=> [:C]