Skip to content

Instantly share code, notes, and snippets.

@psychocandy
Last active December 12, 2015 09:59
Show Gist options
  • Save psychocandy/4755377 to your computer and use it in GitHub Desktop.
Save psychocandy/4755377 to your computer and use it in GitHub Desktop.
A fair implementation of an enum in Ruby. Inspired by Elad Meidar's article on gistflow - http://gistflow.com/posts/682-ruby-enums-approaches
# usage:
# FRUITS = Enum.new(:apples, :oranges)
# FRUITS[:apples] # => 0
# FRUITS[0] # => :apples
class Enum < Hash
def initialize(*members)
super()
@reverse = {}
members.each_with_index { |m,i| self[i] = m }
end
def [](k)
super || @reverse[k]
end
def []=(k,v)
@reverse[v] = k
super
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment