如何在Ruby中实现枚举? [英] How to implement Enums in Ruby?

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

问题描述

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

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.

推荐答案

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

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天全站免登陆