Hello,
I've put together a new enums library / gem [1] for safe
enumeration types in ruby.
Yes, enums are just a set of symbolic keys bound to unique integer numbers.
Why not just use symbols or constants? Do we really need a new enum type
and (yet another) library? Good point.
Let the ruby meta-programming magic work for you :-).
Enum.new( 'Color', :red, :green, :blue ) # -or-
enum :Color, :red, :green, :blue # -or-
enum :Color, [:red, :green, :blue]
See what you get for "free":
Color::RED #=> <Color @key=:red, @value=0>
Color(0) #=> Color::RED -or- <Color @key=:red, @value=0>
Color.zero #=> same as Color(0)
Color.red #=> Color::RED
Color.values #=> [0, 1, 2]
Color.keys #=> [:red, :green, :blue]
Color.members #=> [RED, GREEN, BLUE]
# -or-
# [<Color @key=:red, @value=0>,
# <Color @key=:green, @value=1>,
# <Color @key=:blue, @value=2>]
Color(1) #=> Color::GREEN
Color.value(1) # same as Color(1)
Color[:red] #=> Color::RED
Color.key(:red) # same as Color[:red]
color = Color.red
color.red? #=> true
color == Color.red #=> true
color.value #=> 0
color.key #=> :red
color.blue? #=> false
color == Color.blue #=> false
color.is_a? Enum #=> true
color.is_a? Color #=> true
and some more.
Questions? Comments? Welcome. Cheers. Prost.
PS: The new enums 1.0 library is part of the safe data structures series. [2]
[1] https://github.com/s6ruby/enums
[2] https://github.com/s6ruby/safestruct