Skip to content

canvaswang/ruby-enum

 
 

Repository files navigation

Ruby::Enum

Build Status

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.

About

A handy way to define enums in Ruby.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Ruby 100.0%