Ruby:获取对象(类或模块)中所有常量的完整常量名称的最简单方法

时间:2011-05-26 15:31:35

标签: ruby constants

我有以下结构:

module SomeMod::SubMod
  module Mod1; end
  module Mod2; end
end

我想得到SubMod的所有常量,但我想要一个对Constant的完全限定引用(即。SomeMod::SubMod::Mod1)目前我正在这样做:

SomeMod::SubMod.constants.map{ |constant| SomeMod::SubMod.const_get constant }

有人可以改进吗?我可以删除对SomeMod::SubMod的重复引用吗?

1 个答案:

答案 0 :(得分:2)

SomeMod::SubMod.module_eval{ constants.map{|c| const_get c} }
但是,它并没有那么短。