Ruby中的枚举 [英] Enums in Ruby

查看:157
本文介绍了Ruby中的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中实现枚举成语的最佳方式是什么?我正在寻找可以使用(几乎)像Java / C#枚举的东西。

解决方案

两种方式。符号(:foo 符号)或常量( FOO 符号)。



如果您想提高可读性,而不用乱码与文字字符串相符,则符号是适当的。

  postal_code [:minnesota] = MN
postal_code [:new_york] =NY

具有重要的基础价值。只需声明一个模块来保存你的常量,然后声明该常量。

 模块Foo 
BAR = 1
BAZ = 2
BIZ = 4
end

flags = Foo :: BAR | Foo :: BAZ#flags = 3


What's the best way to implement the enum idiom in Ruby? I'm looking for something which I can use (almost) like the Java/C# enums.

解决方案

Two ways. Symbols (:foo notation) or constants (FOO notation).

Symbols are appropriate when you want to enhance readability without littering code with literal strings.

postal_code[:minnesota] = "MN"
postal_code[:new_york] = "NY"

Constants are appropriate when you have an underlying value that is important. Just declare a module to hold your constants and then declare the constants within that.

module Foo
  BAR = 1
  BAZ = 2
  BIZ = 4
end

flags = Foo::BAR | Foo::BAZ # flags = 3

这篇关于Ruby中的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆