Skip to content

Instantly share code, notes, and snippets.

@johnnypez
Created July 12, 2012 18:44
Show Gist options
  • Save johnnypez/3100073 to your computer and use it in GitHub Desktop.
Save johnnypez/3100073 to your computer and use it in GitHub Desktop.
Enum for Ruby
# example
#
# States = enum %w(Draft Approved Published Trashed)
# => States {Draft, Approved, Published, Trashed}
#
# States::Draft
# => 1
#
# States::Approved
# => 2
#
# States::Published
# => 4
#
# States::Trashed
# => 8
#
# States::Approved | States::Draft
# => 3
#
# States::Approved | States::Published
# => 6
module Enum
def enum(values)
Module.new do |mod|
values.each_with_index{ |v,i| mod.const_set(v.to_s.capitalize, 2**i) }
def mod.inspect
"#{self.name} {#{self.constants.join(', ')}}"
end
end
end
end
include Enum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment