百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
R

ruby-enum

> 编程语言
开源

在 Ruby 中定义枚举的一种方便方法。

189 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

在 Ruby 中定义枚举的一种方便方法。

Ruby::Enum

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

Table of Contents

  • Usage
    • Constants
    • Class Methods
    • Default Value
    • Enumerating
      • Iterating
      • Mapping
      • Reducing
      • Sorting
    • Hashing
      • Retrieving keys and values
      • Mapping keys to values
      • Mapping values to keys
    • Duplicate enumerator keys or duplicate values
    • Inheritance
    • Exhaustive case matcher
    • I18n support
  • Benchmarks
    • Performance
  • Contributing
  • Copyright and License
  • Related Projects

Usage

Enums can be defined and accessed either as constants, or class methods, which is a matter of preference.

Constants

Define enums, and reference them as constants.

ruby
class OrderState
  include Ruby::Enum

  define :CREATED, 'created'
  define :PAID, 'paid'
end
ruby
OrderState::CREATED # 'created'
OrderState::PAID # 'paid'
OrderState::UNKNOWN # raises Ruby::Enum::Errors::UninitializedConstantError
OrderState.keys # [ :CREATED, :PAID ]
OrderState.values # [ 'created', 'paid' ]
OrderState.to_h # { :CREATED => 'created', :PAID => 'paid' }

Class Methods

Define enums, and reference them as class methods.

ruby
class OrderState
  include Ruby::Enum

  define :created, 'created'
  define :paid, 'paid'
end
ruby
OrderState.created # 'created'
OrderState.paid # 'paid'
OrderState.undefined # NoMethodError is raised
OrderState.keys # [ :created, :paid ]
OrderState.values # ['created', 'paid']
OrderState.to_h # { :created => 'created', :paid => 'paid' }

Default Value

The value is optional. If unspecified, the value will default to the key.

ruby
class OrderState
  include Ruby::Enum

  define :UNSPECIFIED
  define :unspecified
end
ruby
OrderState::UNSPECIFIED # :UNSPECIFIED
OrderState.unspecified # :unspecified

Enumerating

Enums support all Enumerable methods.

Iterating

ruby
OrderState.each do |key, enum|
  # key and enum.key are :CREATED, :PAID
  # enum.value is 'created', 'paid'
end
ruby
OrderState.each_key do |key|
  # :CREATED, :PAID
end
ruby
OrderState.each_value do |value|
  # 'created', 'paid'
end

Mapping

ruby
OrderState.map do |key, enum|
  # key and enum.key are :CREATED, :PAID
  # enum.value is 'created', 'paid'
  [enum.value, key]
end

# => [ ['created', :CREATED], ['paid', :PAID] ]

Reducing

ruby
OrderState.reduce([]) do |arr, (key, enum)|
  # key and enum.key are :CREATED, :PAID
  # enum.value is 'created', 'paid'
  arr  [ ['created', :CREATED], ['paid', :PAID] ]

Sorting

ruby
OrderState.sort_by do |key, enum|
  # key and enum.key are :CREATED, :PAID
  # enum.value is 'created', 'paid'
  enum.value.length
end

# => [[:PAID, #], [:CREATED, #]]

Hashing

Several hash-like methods are supported.

Retrieving keys and values

ruby
OrderState.keys
# => [:CREATED, :PAID]

OrderState.values
# => ['created', 'paid']

Mapping keys to values

ruby
OrderState.key?(:CREATED)
# => true

OrderState.value(:CREATED)
# => 'created'

OrderState.key?(:FAILED)
# => false

OrderState.value(:FAILED)
# => nil

Mapping values to keys

ruby
OrderState.value?('paid')
# => true

OrderState.key('paid')
# => :PAID

OrderState.value?('failed')
# => false

OrderState.key('failed')
# => nil

Duplicate enumerator keys or duplicate values

Defining duplicate enums raises Ruby::Enum::Errors::DuplicateKeyError.

ruby
class OrderState
  include Ruby::Enum

  define :CREATED, 'created'
  define :CREATED, 'recreated' # raises DuplicateKeyError
end

Defining a duplicate value raises Ruby::Enum::Errors::DuplicateValueError.

ruby
class OrderState
  include Ruby::Enum

  define :CREATED, 'created'
  define :RECREATED, 'created' # raises DuplicateValueError
end

The DuplicateValueError exception is raised to be consistent with the unique key constraint. Since keys are unique, there needs to be a way to map values to keys using OrderState.value('created').

Inheritance

When inheriting from a Ruby::Enum class, all defined enums in the parent class will be accessible in subclasses as well. Subclasses can also provide extra enums, as usual.

ruby
class OrderState
  include Ruby::Enum

  define :CREATED, 'CREATED'
  define :PAID, 'PAID'
end

class ShippedOrderState  NOTE: This will add checks at runtime which might lead to worse performance. See [benchmarks](#benchmarks).

> NOTE: `:else` is a reserved keyword if you want to use `Ruby::Enum::Case`.

```ruby
class Color  -> { "order is green or blue" },
  Color::YELLOW => -> { "order is yellow" },
  Color::RED => -> { "order is red" },
})

It also supports default/else:

ruby
color = Color::RED
Color.Case(color, {
  [Color::GREEN, Color::BLUE] => -> { "order is green or blue" },
  else: -> { "order is yellow or red" },
})

I18n support

This gem has an optional dependency to i18n. If it's available, the error messages will have a nice description and can be translated. If it's not available, the errors will only contain the message keys.

ruby
# Add this to your Gemfile if you want to have a nice error description instead of just a message key.
gem "i18n"

Benchmarks

Benchmark scripts are defined in the benchmarks folder and can be run with Rake:

bash
rake benchmark:basic
rake benchmark:case
rake benchmark:inheritance

Performance

Constant access (e.g. Colors::RED) has no measurable overhead versus a plain Ruby constant, since it's just a constant lookup either way. Basic operations backed by a hash lookup - value, key, key?, value?, keys, values - carry some overhead (roughly 3-5x) compared to using a plain Hash directly, due to the extra method dispatch and object wrapping Ruby::Enum does internally. Run rake benchmark:basic to measure this on your own machine.

This overhead is constant regardless of how deep a subclass hierarchy is - keys, key?, value?, key, value, to_h, parse and each merge and memoize enums inherited from superclasses, so a subclass' lookups are effectively as fast as the base class' (see rake benchmark:inheritance).

The one notable exception is Ruby::Enum::Case, whose exhaustive case-like matcher is significantly slower (on the order of 50-100x, see rake benchmark:case) than a native Ruby case/when statement, since it builds and evaluates lambdas on every call rather than being optimized by the Ruby VM. Prefer a native case statement in hot code paths and reserve Ruby::Enum::Case for cases where its exhaustiveness check is worth the overhead.

For most applications this overhead is negligible in absolute terms (low single-digit microseconds per call), but it's worth being aware of in very hot code paths.

Contributing

You're encouraged to contribute to ruby-enum. See CONTRIBUTING for details.

Copyright and License

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

This project is licensed under the MIT License.

Related Projects

  • typesafe_enum: Typesafe enums, inspired by Java.
  • renum: A readable, but terse enum.

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubyenumenumerableenumsruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言