A Ruby implementation of enumerated type for educational purposes.
Heavily based on Crystal.
An enum is a set of integer values, where each value has an associated name.
For example:
require 'enum'
class Color < Enum
member :Red # 0
member :Green # 1
member :Blue # 2
end
Values start with the value 0
and are incremented by one, but can be overwritten.
To get the underlying value you invoke value
on it:
Color::Green.value # ⇒ 1
An enum can be created from an integer:
Color.new(1).to_s # ⇒ "Green"
Values that don’t correspond to enum’s constants are allowed:
the value will still be of type Color
, but when printed you will get the underlying value:
Color.new(10).to_s # ⇒ "10"
This method is mainly intended to convert integers from C to enums in Ruby.
Color::Red.red? # ⇒ true
Color::Blue.red? # ⇒ false
def paint(color)
case color
when Color::Red
# ...
else
# Unusual, but still can happen.
raise "Unknown color: #{color}"
end
end