Enum-like behavior for Ruby, heavily inspired by this and improved upon another blog post.
class Colors
include Ruby::Enum
define :RED, "red"
define :GREEN, "green"
endColors::RED # "red"
Colors::GREEN # "green"
Colors::UNDEFINED # raises Ruby::Enum::Errors::UninitializedConstantError
Colors.keys # [ :RED, :GREEN ]
Colors.values # [ "red", "green" ]
Colors.to_h # { :RED => "red", :GREEN => "green" }Colors.each do |key, enum|
# key and enum.key is :RED, :GREEN
# enum.value is "red", "green"
endColors.map do |key, enum|
# key and enum.key is :RED, :GREEN
# enum.value is "red", "green"
[enum.value, key]
end
# => [ ['red', :RED], ['green', :GREEN] ]Colors.reduce([]) do |arr, (key, enum)|
# key and enum.key is :RED, :GREEN
# enum.value is "red", "green"
arr << [enum.value, key]
end
# => [ ['red', :RED], ['green', :GREEN] ]Colors.sort_by do |key, enum|
# key and enum.key is :RED, :GREEN
# enum.value is "red", "green"
enum.value
end
# => [ [:GREEN, #<Colors:...>], [:RED, #<Colors:...>] ]Colors.keys
# => [:RED, :GREEN]
Colors.values
# => ["red", "green"]Colors.key?(:RED)
# => true
Colors.value(:RED)
# => "red"
Colors.key?(:BLUE)
# => false
Colors.value(:BLUE)
# => nilColors.value?('green')
# => true
Colors.key('green')
# => :GREEN
Colors.value?('yellow')
# => false
Colors.key('yellow')
# => nilDefining duplicate enums will raise a Ruby::Enum::Errors::DuplicateKeyError. Moreover a duplicate
value is not allowed. Defining a duplicate value will raise a Ruby::Enum::Errors::DuplicateKeyError.
The following declarations will both raise an exception:
class Colors
include Ruby::Enum
define :RED, "red"
define :RED, "my red" # will raise a DuplicateKeyError exception
end
# The following will raise a DuplicateValueError
class Colots
include Ruby::Enum
define :RED, 'red'
define :SOME, 'red' # Boom
endThe DuplicateValueError exception is thrown to be consistent with the unique key constraint.
Since keys are unique there is no way to map values to keys using Colors.key('red')
You're encouraged to contribute to this gem. See CONTRIBUTING for details.
Copyright (c) 2013-2015, Daniel Doubrovkine and Contributors.
This project is licensed under the MIT License.
- typesafe_enum: Typesafe enums, inspired by Java.
- renum: A readable, but terse enum.