15

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’ for Constants::module

....

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

themirror
  • 9,963
  • 7
  • 46
  • 79
  • A useful link for this question: http://stackoverflow.com/questions/2309255/how-do-i-get-constants-defined-by-rubys-module-class-via-reflection. – Ray Toal Jul 15 '11 at 20:15

1 Answers1

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

Constants.constants.each do |c|
  puts "#{c}: #{Constants.const_get(c)}"
end
#=> "C1: foo"
#=> "C2: bar"
fl00r
  • 82,987
  • 33
  • 217
  • 237