Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
A handy way to define enums in Ruby.
Ruby
branch: master

README.md

Ruby::Enum

Gem Version Build Status Dependency Status Code Climate

Enum-like behavior for Ruby, heavily inspired by this and improved upon another blog post.

Usage

class Colors
  include Ruby::Enum

  define :RED, "red"
  define :GREEN, "green"
end

Referencing

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" }

All Enumerable methods are supported.

Iterating

Colors.each do |key, enum|
  # key and enum.key is :RED, :GREEN
  # enum.value is "red", "green"
end

Mapping

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] ]

Reducing

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] ]

Sorting

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:...>] ]

Contributing

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 and License

Copyright (c) 2013-2014, Daniel Doubrovkine and Contributors.

This project is licensed under the MIT License.

Something went wrong with that request. Please try again.