2011-07-15 78 views
14

我剛開始在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 

....

有迭代的一個很好的方式通過一個常量列表?

+0

一個有用的鏈接,這樣的疑問:http://stackoverflow.com/questions/2309255/how-do-i-get-constants-defined-by-rubys-module-class-via-reflection。 –

回答

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

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

Typo Constant =>常量 –

+0

@Ray Toal,yeap,thanks – fl00r