Emulating enums
suggest changeRuby has no enum keyword. When other languages reach for an enum (a fixed, named set of values such as order states, log levels or card suits), Ruby programmers use one of several idioms:
| Approach | Good for |
|---|---|
| Symbols plus a frozen list | simple tags, hash keys, method arguments |
| Module constants | values that must map to integers or strings (protocols, C APIs) |
| Bit flags | combinable options (permissions) |
| A class with a fixed set of frozen instances | values that carry data and behavior, ordering, type checks |
Data.define subclass |
a lightweight variant of the above |
Rails enum |
a database column backed by an integer or string |
The examples were run with Ruby 4.0 and Active Record 8.1.
Symbols and a frozen list
The simplest enum is a set of symbols. A symbol is a unique object that is always frozen, so :draft is the same object everywhere it appears and comparing two symbols is as fast as comparing integers:
p :draft.frozen?
p :draft.equal?(:draft)
p "draft".equal?("draft")
true
true
false
Nothing stops a caller from passing :drafts instead of :draft, though. Put the allowed values in a frozen constant and check against it at the boundary:
STATUSES = %i[draft published archived].freeze
def set_status(post, status)
unless STATUSES.include?(status)
raise ArgumentError, "invalid status #{status.inspect}, expected one of #{STATUSES.inspect}"
end
post[:status] = status
end
post = {}
set_status(post, :published)
p post
begin
set_status(post, :deleted)
rescue ArgumentError => e
puts e.message
end
p STATUSES.index(:archived)
p STATUSES.include?("draft")
p STATUSES.include?("draft".to_sym)
{status: :published}
invalid status :deleted, expected one of [:draft, :published, :archived]
2
false
true
The list gives you iteration (STATUSES.each), an ordinal (STATUSES.index) and validation. Note that a string from user input or JSON is not equal to a symbol; convert it with to_sym first (only after checking it, or by looking it up, if the input is untrusted).
Symbols are the right choice most of the time: they work as hash keys, in case statements and in pattern matching with no extra code. Their weakness is that the values have no behavior and typos in the code that uses them are found only at runtime.
Module constants
When each name needs a specific value, define constants in a module. This is common when the values come from a file format, network protocol or C library:
module Color
RED = 1
GREEN = 2
BLUE = 3
end
p Color::GREEN
p Color.constants
p Color.constants.map { |name| [name, Color.const_get(name)] }.to_h
# reverse lookup: value -> name
def color_name(value)
Color.constants.find { |name| Color.const_get(name) == value }
end
p color_name(3)
p color_name(42)
begin
Color::PURPLE
rescue NameError => e
puts e.message
end
p Color.const_defined?(:RED)
p Color.const_get("BLUE")
2
[:RED, :GREEN, :BLUE]
{RED: 1, GREEN: 2, BLUE: 3}
:BLUE
nil
uninitialized constant Color::PURPLE
true
3
Compared to bare symbols, a misspelled constant (Color::PURPLE) fails loudly with NameError as soon as the line runs. Module#constants returns the names in definition order, which gives you iteration and reverse lookup.
The downside is that the values are plain integers: Color::RED == 1 is true, Color::RED + Color::GREEN is legal, and a method that expects a color will happily accept the number of items in a cart. Ruby constants can also be reassigned (with a warning). See Constants for details.
Bit flags
If values can be combined, give each one its own bit and combine them with |. The Integer methods allbits?, anybits? and nobits? make the tests readable:
module Permission
READ = 1 << 0
WRITE = 1 << 1
EXECUTE = 1 << 2
ALL = READ | WRITE | EXECUTE
def self.names(mask)
constants.reject { |c| c == :ALL }
.select { |c| mask & const_get(c) != 0 }
end
end
perms = Permission::READ | Permission::WRITE
p perms
p perms.to_s(2)
p perms.anybits?(Permission::WRITE)
p perms.allbits?(Permission::READ | Permission::EXECUTE)
p perms.anybits?(Permission::EXECUTE | Permission::WRITE)
perms |= Permission::EXECUTE
p perms == Permission::ALL
perms &= ~Permission::WRITE
p Permission.names(perms)
3
"11"
true
false
true
true
[:READ, :EXECUTE]
For flags that never leave the process, a Set of symbols (Set[:read, :write]) is easier to read and debug. Use integers when the mask is stored in a database column or passed to an external API. More on bitwise operators in Bit manipulation.
A class with a fixed set of instances
For a real enum type (one where values are objects of their own class, can be ordered, and carry data and methods) create the instances once, store them in constants, and make new private so nobody can create more:
class Priority
include Comparable
attr_reader :name, :level
def initialize(name, level)
@name = name
@level = level
freeze
end
private_class_method :new
LOW = new(:low, 1)
MEDIUM = new(:medium, 2)
HIGH = new(:high, 3)
ALL = [LOW, MEDIUM, HIGH].freeze
class << self
include Enumerable
def each(&) = ALL.each(&)
def [](name)
find { |p| p.name == name.to_sym } or
raise ArgumentError, "unknown priority: #{name.inspect}"
end
end
def <=>(other)
level <=> other.level if other.is_a?(Priority)
end
def to_s = name.to_s
def inspect = "#<Priority #{name}>"
end
p Priority::HIGH
puts Priority::HIGH
p Priority::HIGH > Priority::LOW
p Priority.map(&:name)
p Priority.max
p Priority["medium"]
p Priority[:low].equal?(Priority::LOW)
p [Priority::HIGH, Priority::LOW, Priority::MEDIUM].sort
p Priority::LOW.between?(Priority::LOW, Priority::MEDIUM)
p Priority.select { |pr| pr >= Priority::MEDIUM }
begin
Priority.new(:urgent, 4)
rescue NoMethodError => e
puts e.message
end
begin
Priority["urgent"]
rescue ArgumentError => e
puts e.message
end
p Priority::HIGH.frozen?
#<Priority high>
high
true
[:low, :medium, :high]
#<Priority high>
#<Priority medium>
true
[#<Priority low>, #<Priority medium>, #<Priority high>]
true
[#<Priority medium>, #<Priority high>]
private method 'new' called for class Priority
unknown priority: "urgent"
true
The pieces:
private_class_method :newcomes afterinitializebut before the constants, so the class body can still callnewwhile outside code can't.freezein the constructor makes each value immutable. Enum values are shared by the whole program, so they must not change.- Including
Comparableand defining<=>gives<,>,between?,clampand sorting. Returningnilfor other types makesPriority::HIGH > 3raiseArgumentErrorinstead of returning nonsense. See Comparable. - Extending the singleton class with
Enumerableand aneachmethod lets you callmap,select,max,findand friends on the class itself. Priority[...]converts a string or symbol (from a form, a config file, JSON) into a value, failing on unknown names.
Because there is exactly one instance per value, identity comparison works and these objects are cheap to use as hash keys.
A reusable Enum base class
Writing the same boilerplate for every enum gets old. A small base class with a value macro handles constants, ordinals, lookup and predicates. Save it as enum.rb:
class Enum
include Comparable
attr_reader :name, :ordinal
def initialize(name, ordinal, **attrs)
@name = name
@ordinal = ordinal
attrs.each { |key, val| instance_variable_set(:"@#{key}", val) }
freeze
end
class << self
include Enumerable
def value(name, **attrs)
@values ||= []
inst = new(name, @values.size, **attrs)
attrs.each_key { |key| attr_reader key unless method_defined?(key) }
const_set(name.to_s.upcase, inst)
define_method(:"#{name}?") { equal?(inst) }
@values << inst
inst
end
def values = @values.dup.freeze
def each(&) = @values.each(&)
def [](name)
find { |v| v.name == name.to_sym } or
raise KeyError, "#{self.name}: unknown value #{name.inspect}"
end
def inherited(subclass)
super
subclass.private_class_method :new
end
end
def <=>(other)
ordinal <=> other.ordinal if other.instance_of?(self.class)
end
def to_s = name.to_s
def inspect = "#{self.class}::#{name.to_s.upcase}"
# keep values unique across dup/clone and Marshal
def dup = self
def clone(freeze: true) = self
def _dump(_level) = name.to_s
def self._load(str) = self[str]
end
How it works:
value :earth, mass: ...creates an instance, assigns it to the constantEARTHwithconst_set, defines a reader for every extra attribute and a predicate methodearth?.ordinalis the position in declaration order, used for comparison.- The
inheritedhook makesnewprivate in every subclass. dupandclonereturnself, the same as symbols and integers do, and_dump/_loadmakeMarshalreturn the existing instance rather than a copy. Without them a round trip throughMarshal(used by some caches and byDRb) would produce a secondEARTHthat is notequal?to the first.
Values can carry data, and the subclass can add methods that use it. This is the classic "planets" example from Java's enum documentation:
require_relative "enum"
class Planet < Enum
G = 6.674e-11
value :mercury, mass: 3.303e23, radius: 2.4397e6
value :earth, mass: 5.976e24, radius: 6.37814e6
value :jupiter, mass: 1.9e27, radius: 7.1492e7
def surface_gravity = G * mass / (radius**2)
end
p Planet::EARTH
p Planet.values
p Planet::EARTH.mass
p Planet::EARTH.ordinal
p Planet::EARTH.earth?
p Planet::EARTH.jupiter?
Planet.each { |pl| printf("%-8s %6.2f m/s^2\n", pl, pl.surface_gravity) }
p Planet.max_by(&:surface_gravity)
p Planet::MERCURY < Planet::JUPITER
p Planet["jupiter"]
begin
Planet[:pluto]
rescue KeyError => e
puts e.message
end
copy = Marshal.load(Marshal.dump(Planet::EARTH))
p copy.equal?(Planet::EARTH)
p Planet::EARTH.dup.equal?(Planet::EARTH)
Planet::EARTH
[Planet::MERCURY, Planet::EARTH, Planet::JUPITER]
5.976e+24
1
true
false
mercury 3.70 m/s^2
earth 9.80 m/s^2
jupiter 24.81 m/s^2
Planet::JUPITER
true
Planet::JUPITER
Planet: unknown value :pluto
true
true
Behavior per value
When each value needs different behavior, store a lambda as an attribute instead of writing a case statement in every method:
require_relative "enum"
class Operation < Enum
value :add, symbol: "+", fn: ->(a, b) { a + b }
value :subtract, symbol: "-", fn: ->(a, b) { a - b }
value :multiply, symbol: "*", fn: ->(a, b) { a * b }
value :divide, symbol: "/", fn: ->(a, b) { a.fdiv(b) }
def apply(a, b) = fn.call(a, b)
def self.from_symbol(sym) = find { |op| op.symbol == sym }
end
Operation.each { |op| puts "6 #{op.symbol} 4 = #{op.apply(6, 4)}" }
p Operation.from_symbol("*")
6 + 4 = 10
6 - 4 = 2
6 * 4 = 24
6 / 4 = 1.5
Operation::MULTIPLY
Enums as state machines
Enums often model states. Keeping the allowed transitions next to the values puts all the rules in one place:
require_relative "enum"
class TicketState < Enum
value :open
value :in_progress
value :resolved
value :closed
TRANSITIONS = {
open: %i[in_progress closed],
in_progress: %i[open resolved],
resolved: %i[closed in_progress],
closed: []
}.freeze
def next_states = TRANSITIONS.fetch(name).map { |n| self.class[n] }
def can_become?(other) = next_states.include?(other)
def final? = next_states.empty?
end
class Ticket
attr_reader :state
def initialize = @state = TicketState::OPEN
def transition_to(new_state)
unless state.can_become?(new_state)
raise ArgumentError, "can't go from #{state} to #{new_state}"
end
@state = new_state
end
end
t = Ticket.new
t.transition_to(TicketState::IN_PROGRESS)
t.transition_to(TicketState::RESOLVED)
p t.state
p t.state.next_states
begin
t.transition_to(TicketState::OPEN)
rescue ArgumentError => e
puts e.message
end
p TicketState.select(&:final?)
TicketState::RESOLVED
[TicketState::CLOSED, TicketState::IN_PROGRESS]
can't go from resolved to open
[TicketState::CLOSED]
case, pattern matching and JSON
case/when compares with ===, which for ordinary objects is ==, so enum instances work in case statements and in pattern matching with no extra code. To send a value over the wire, serialize its name and convert back with []:
require_relative "enum"
require "json"
class OrderState < Enum
value :pending
value :paid
value :shipped
value :cancelled
def to_json(*args) = to_s.to_json(*args)
end
def describe(state)
case state
when OrderState::PENDING then "waiting for payment"
when OrderState::PAID then "ready to ship"
when OrderState::SHIPPED then "on its way"
when OrderState::CANCELLED then "cancelled"
else raise ArgumentError, "unhandled state #{state.inspect}"
end
end
OrderState.each { |s| puts "#{s}: #{describe(s)}" }
# pattern matching works too, since === is ==
order = { id: 7, state: OrderState::PAID }
case order
in { state: OrderState::PAID | OrderState::PENDING => s }
puts "order #{order[:id]} is open (#{s})"
in { state: }
puts "order #{order[:id]} is closed (#{state})"
end
json = JSON.generate({ id: 7, state: OrderState::SHIPPED })
puts json
data = JSON.parse(json, symbolize_names: true)
p OrderState[data[:state]]
pending: waiting for payment
paid: ready to ship
shipped: on its way
cancelled: cancelled
order 7 is open (paid)
{"id":7,"state":"shipped"}
OrderState::SHIPPED
Store the name, not the ordinal, in files and databases. Names survive reordering and inserting new values; ordinals don't.
The else raise branch in describe is a runtime substitute for the exhaustiveness checking that compilers do for enums in Rust, Swift or Kotlin. For lookup tables keyed by enum values, you can check at load time that every value is covered:
require_relative "enum"
class Level < Enum
value :debug
value :info
value :warn
value :error
end
COLORS = {
Level::DEBUG => :gray,
Level::INFO => :white,
Level::WARN => :yellow
}.freeze
missing = Level.values - COLORS.keys
abort "no color for: #{missing.map(&:to_s).join(', ')}" unless missing.empty?
no color for: error
Adding a value to Level now breaks the program on startup (or in a test that requires the file), not the first time someone logs an error.
Using Data.define
Data.define (Ruby 3.2+) generates an immutable value class with a keyword constructor, to_h, equality and pattern matching support. Subclassing it is a compact way to write an enum whose values are records:
class Suit < Data.define(:name, :symbol, :color)
private_class_method :new
CLUBS = new(:clubs, "♣", :black)
DIAMONDS = new(:diamonds, "♦", :red)
HEARTS = new(:hearts, "♥", :red)
SPADES = new(:spades, "♠", :black)
def self.all = [CLUBS, DIAMONDS, HEARTS, SPADES]
def to_s = symbol
end
p Suit::HEARTS
puts Suit.all.join(" ")
p Suit.all.select { |s| s.color == :red }.map(&:name)
p Suit::HEARTS.frozen?
p Suit::HEARTS.to_h
case Suit::SPADES
in { color: :black, name: }
puts "black suit: #{name}"
end
begin
Suit.new(name: :stars, symbol: "*", color: :gold)
rescue NoMethodError => e
puts e.message
end
#<data Suit name=:hearts, symbol="♥", color=:red>
♣ ♦ ♥ ♠
[:diamonds, :hearts]
true
{name: :hearts, symbol: "♥", color: :red}
black suit: spades
private method 'new' called for class Suit
Use class Suit < Data.define(...) rather than Suit = Data.define(...) do ... end. Constants assigned inside a block belong to the surrounding scope, so with the block form CLUBS would become a top-level constant, not Suit::CLUBS.
There is one hole: Data#with copies a value with some fields changed and doesn't go through new, so Suit::HEARTS.with(color: :blue) creates a fifth suit. Data objects compare by value rather than identity, so such a copy is not equal to any real suit, but if that matters use the class-based approach above.
Rails: ActiveRecord enum
In Rails apps, enum maps a database column (usually an integer) to a set of names and generates predicates, bang methods and scopes:
require "active_record"
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Schema.verbose = false
ActiveRecord::Schema.define do
create_table :articles do |t|
t.string :title
t.integer :status, null: false, default: 0
end
end
class Article < ActiveRecord::Base
enum :status, { draft: 0, published: 1, archived: 2 }, validate: true
end
a = Article.create!(title: "Enums")
p a.status
p a.draft?
a.published!
p a.status
p a.read_attribute_before_type_cast(:status)
p Article.statuses
p Article.published.count
p Article.where(status: :archived).to_sql
a.status = :bogus
p a.valid?
p a.errors.full_messages
"draft"
true
"published"
1
{"draft" => 0, "published" => 1, "archived" => 2}
1
"SELECT \"articles\".* FROM \"articles\" WHERE \"articles\".\"status\" = 2"
false
["Status is not included in the list"]
Always give the mapping as an explicit hash. With the array form (enum :status, [:draft, :published]) the stored integer is the array index, and reordering the array silently changes the meaning of every row in the table. Without validate: true, assigning an unknown value raises ArgumentError instead of producing a validation error.
Which one to pick
- Start with symbols and a frozen list of allowed values. That is what Ruby's own APIs do (
2.5.round(half: :even),str.encode("UTF-8", invalid: :replace)). - Use module constants when the values are numbers or strings defined by something outside your program.
- Use bit flags for combinable options that need a compact integer form.
- Use an enum class when values have attributes or behavior, need ordering, or when you want a method to reject anything that isn't a real value (
raise TypeError unless state.is_a?(OrderState)). - In Rails models, use the built-in
enumwith an explicit hash.
Whichever you choose, freeze the values, keep the list of allowed values in one place, and convert external input (strings from forms, JSON, the database) at the edge of the program with a lookup that fails on unknown names.