Ruby enums. They're not meant to be. Otherwise, they would probably be in the Standard Library, no? After all, Struct
is in there. But sometimes, you just gotta have something a bit more concrete than a symbol.
Enter this class. The Enum
class works almost exactly like the Struct
one does: you pass it a list of symbols, and it hands you back a class. The trick is, you don't make any instances of the class; it is the enum. Allow me to demonstrate:
Lives = Enum.new(:NONE, :ONE, :TWO, :MORE)
Lives.each { |element| puts element } # => "NONE\nONE\nTWO\nMORE"
Lives::NONE # => 0
That's all there is to it. Klass::Constant
is how things work (assuming you used Klass = Enum.new(:Constant)
). There's Klass.each
and Klass.map
too, if you feel like cycling through them.
What if you wanted something... fancier?
enum {
ALPHA = 1
BRAVO
} // This is psuedo-C, by the way
Well, we can work with that:
Callsigns = Enum.new(1, :ALPHA, :BRAVO)
Callsigns::ALPHA # => 1, not 0
Now, kick back, relax, and enjoy the code.