在Ruby中实现枚举习语的最佳方法是什么?我正在寻找一些东西,我可以使用(几乎)像Java/ c#枚举。


当前回答

另一种方法是使用带有包含名称和值的散列的Ruby类,如下面的RubyFleebie博客文章所述。这允许您轻松地在值和常量之间进行转换(特别是如果您添加了一个类方法来查找给定值的名称)。

其他回答

最近我们发布了一个在Ruby中实现枚举的gem。在我的帖子中,你会找到你的问题的答案。我还描述了为什么我们的实现比现有的更好(实际上在Ruby中有很多这个特性的实现)。

如果您担心符号的拼写错误,请确保您的代码在访问具有不存在键的值时引发异常。你可以使用fetch而不是[]:

my_value = my_hash.fetch(:key)

或者在默认情况下,如果你提供了一个不存在的键,让哈希抛出一个异常:

my_hash = Hash.new do |hash, key|
  raise "You tried to access using #{key.inspect} when the only keys we have are #{hash.keys.inspect}"
end

如果散列已经存在,你可以添加异常引发行为:

my_hash = Hash[[[1,2]]]
my_hash.default_proc = proc do |hash, key|
  raise "You tried to access using #{key.inspect} when the only keys we have are #{hash.keys.inspect}"
end

通常情况下,您不必担心常量的拼写安全问题。如果你拼错了常量名,通常会引发异常。

如果你使用的是Rails 4.2或更高版本,你可以使用Rails枚举。

Rails现在默认有枚举,不需要包含任何宝石。

这与Java、c++的枚举非常相似(并且具有更多的特性)。

引用自http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html:

class Conversation < ActiveRecord::Base
  enum status: [ :active, :archived ]
end

# conversation.update! status: 0
conversation.active!
conversation.active? # => true
conversation.status  # => "active"

# conversation.update! status: 1
conversation.archived!
conversation.archived? # => true
conversation.status    # => "archived"

# conversation.update! status: 1
conversation.status = "archived"

# conversation.update! status: nil
conversation.status = nil
conversation.status.nil? # => true
conversation.status      # => nil

我认为实现类似类型的枚举的最好方法是使用符号,因为它们的行为非常像整数(当涉及到性能时,object_id用于进行比较);你不需要担心索引,它们在你的代码xD中看起来非常整洁

也许最好的轻量级方法是

module MyConstants
  ABC = Class.new
  DEF = Class.new
  GHI = Class.new
end

这样,值就有了关联的名称,就像在Java/ c#中一样:

MyConstants::ABC
=> MyConstants::ABC

要获得所有的值,可以这样做

MyConstants.constants
=> [:ABC, :DEF, :GHI] 

如果你想要枚举的序号值,你可以这样做

MyConstants.constants.index :GHI
=> 2