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

lilijreey · October 05, 2018 · Last by lilijreey replied at October 09, 2018 · 2070 hits

请问 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
Reply to nouse

枚举和强类型没关系

You need to Sign in before reply, if you don't have an account, please Sign up first.