开发者

Ruby: Iterating through Constants

开发者 https://www.devze.com 2023-03-21 02:42 出处:网络
I\'m just starting to use constants in Ruby. I have module Constants C1 = \"foo\" C2 = \"bar\" end I would like to do

I'm just starting to use constants in Ruby.

I have

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

I would like to do

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

but it says

undefined method ‘each’ f开发者_如何学编程or Constants::module

....

Is there a nice way of iterating through a list of constants?


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

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

精彩评论

暂无评论...
验证码 换一张
取 消