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"
end
Colors::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"
end
Colors.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:...>] ]
You're encouraged to contribute to this gem.
- Fork this project.
- Make changes, write tests.
- Updated CHANGELOG.
- Make a pull request, bonus points for topic branches.
Copyright (c) 2013-2014, Daniel Doubrovkine and Contributors.
This project is licensed under the MIT License.