Last active
December 12, 2015 09:59
-
-
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
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
# 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