Skip to content

Instantly share code, notes, and snippets.

@ka8725
Created April 25, 2012 21:17
Show Gist options
  • Save ka8725/2493524 to your computer and use it in GitHub Desktop.
Save ka8725/2493524 to your computer and use it in GitHub Desktop.
Enums for Ruby
def enum(*values, &class_body)
Class.new( Class.new(&class_body) ) do
attr_reader :ordinal
def initialize(ordinal, *args, &blk)
super(*args, &blk)
@ordinal = ordinal
end
values.each_with_index do |(name, *parameters), i|
const_set(name, new(i, *parameters))
end
class <<self
private :new
end
end
end
# Usage:
MyEnum = enum([:VALUE1, "Value 1"], [:VALUE2, "Value 2"]) do
attr_reader :str
def initialize(str)
@str = str
end
end
MyEnum::VALUE1.str #=> "Value 1"
MyEnum::VALUE2.ordinal #=> 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment