Created
April 25, 2012 21:17
-
-
Save ka8725/2493524 to your computer and use it in GitHub Desktop.
Enums for Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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