Daniel Lubarov

Enums in Ruby

There are many approaches to enumerated types in Ruby. Here's my preferred approach, which I haven't seen elsewhere:

module MyConstants
  ABC = Class.new
  DEF = Class.new
  GHI = Class.new
end

This gives each value an associated name:

MyConstants::ABC
=> MyConstants::ABC

To get all values, you can do

MyConstants.constants
=> [:ABC, :DEF, :GHI]

If you need ordinal values, you can do

MyConstants.constants.index :GHI
=> 2