Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Iterating through Constants

Tags:

ruby

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?

like image 460
themirror Avatar asked Jul 15 '11 20:07

themirror


1 Answers

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

Constants.constants.each do |c|
  puts "#{c}: #{Constants.const_get(c)}"
end
#=> "C1: foo"
#=> "C2: bar"
like image 61
fl00r Avatar answered Sep 21 '22 13:09

fl00r