【问题标题】:Ruby: Iterating through ConstantsRuby:遍历常量
【发布时间】:2011-07-15 20:10:25
【问题描述】:

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

我有

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

我想做

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

但它说

undefined method ‘each’ for Constants::module

....

有没有一种很好的方法来遍历常量列表?

【问题讨论】:

标签: ruby


【解决方案1】:
module Constants
  C1 = "foo"
  C2 = "bar"
end

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

【讨论】:

    猜你喜欢
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 2015-03-15
    相关资源
    最近更新 更多