Ruby:迭代常量

时间:2011-07-15 20:10:25

标签: ruby

我刚开始在Ruby中使用常量。

我有

module Constants
  C1 = "foo"
  C2 = "bar"
end

我想做

Constants.each do |c|
  #do something with each one
end

但它说

undefined method ‘each’ for Constants::module

...

有没有一种很好的方法来迭代常量列表?

1 个答案:

答案 0 :(得分:36)

module Constants
  C1 = "foo"
  C2 = "bar"
end

Constants.constants.each do |c|
  puts "#{c}: #{Constants.const_get(c)}"
end
#=> "C1: foo"
#=> "C2: bar"