Ruby-EnumRuby 快速定义枚举

联合创作 · 2023-10-01 11:23

Ruby-Enum 是一组 Ruby 定义枚举的便捷方式,可用于快速定义枚举。

用法

枚举可以作为常量或类方法定义和访问。

常量

定义枚举,并作为常量引用

class OrderState
  include Ruby::Enum

  define :CREATED, 'created'
  define :PAID, 'paid'
end
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 OrderState
  include Ruby::Enum

  define :created, 'created'
  define :paid, 'paid'
end
OrderState.created # 'created'
OrderState.paid # 'paid'
OrderState.undefined # NoMethodError is raised
OrderState.keys # [ :created, :paid ]
OrderState.values # ['created', 'paid']

默认值

指可选,不选的话默认为 key。

class OrderState
  include Ruby::Enum

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

枚举

支持所有Enumerable方法

迭代

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

映射

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] ]

排序

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

# => [[:PAID, #<OrderState:0x0 @key=:PAID, @value="paid">], [:CREATED, #<OrderState:0x1 @key=:CREATED, @value="created">]]
浏览 10
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报