Skip to content

Instantly share code, notes, and snippets.

@benolee
Created July 27, 2014 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benolee/4b3b296ce90716835e3a to your computer and use it in GitHub Desktop.
Save benolee/4b3b296ce90716835e3a to your computer and use it in GitHub Desktop.
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