新手问题 ruby 中如何定义枚举值

lilijreey · 2018年10月05日 · 最后由 lilijreey 回复于 2018年10月09日 · 2078 次阅读

请问 ruby 中有类似 C enum 这种机制吗,最好是和 Java 的 enum class 一样?

hash = Hash.new
%w(cat dog wombat).each_with_index { |item, index|
  hash[item] = index
}
hash   #=> {"cat"=>0, "dog"=>1, "wombat"=>2}

这个算不算 enum ? https://ruby-doc.org/core-2.5.1/Enumerable.html#method-i-each_with_index

并没有你要的枚举类型

Ruby 本身就不是强类型,enum 没有意义

有类似的

1. active enum

2. module

module Gender
  FEMALE = 1 # 女性
  MALE   = 2 # 男性
  LABELS = { FEMALE => '女性', MALE => '男性' } # 也可以使用I18n来定义
end

Gender::FEMALE
Gender::MALE
nouse 回复

枚举和强类型没关系

需要 登录 后方可回复, 如果你还没有账号请 注册新账号