Created
July 27, 2014 06:47
-
-
Save benolee/4b3b296ce90716835e3a to your computer and use it in GitHub Desktop.
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 blk = Proc.new | |
m = Module.new | |
o = Object.new | |
o.instance_eval { | |
@enum_idx = -1 | |
@enum_mod = m | |
def method_missing(n, *a) | |
n =~ /([A-Z][A-Z_]*)(=)?/ | |
raise "bad enum name #{n}" unless $1 | |
if $2 | |
v = a[0] | |
else | |
v = @enum_idx + 1 | |
end | |
@enum_idx = v | |
@enum_mod.const_set($1, v) | |
nil | |
end | |
instance_exec(self, &blk) | |
} | |
m | |
end | |
E = enum { |e| | |
e.FOO | |
e.BAR | |
e.BAZ = 42 | |
e.FUGA_QUUX | |
} | |
p E::FOO #=> 0 | |
p E::BAR #=> 1 | |
p E::BAZ #=> 42 | |
p E::FUGA_QUUX #=> 43 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment