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

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

问题描述

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

解决方案

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

当你想提高可读性而不用文字字符串乱扔代码时,符号是合适的.

postal_code[:minnesota] = "MN";postal_code[:new_york] = "纽约";

当您具有重要的潜在价值时,常量是合适的.只需声明一个模块来保存您的常量,然后在其中声明常量.

模块 Foo酒吧 = 1巴兹 = 2企业 = 4结尾标志 = Foo::BAR |Foo::BAZ # 标志 = 3

于 2021-01-17 添加

如果您正在传递枚举值(例如,将其存储在数据库中)并且您需要能够将值转换回符号,则可以使用两种方法的混搭

COMMODITY_TYPE = {货币:1,投资:2,}定义商品类型字符串(值)COMMODITY_TYPE.key(值)结尾COMMODITY_TYPE[:货币]

这种方法的灵感来自于 andrew-grimm 的回答 https://stackoverflow.com/a/5332950/13468

我还建议您通读这里的其余答案,因为有很多方法可以解决这个问题,而且实际上归结为您关心的其他语言枚举的内容

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

Added 2021-01-17

If you are passing the enum value around (for example, storing it in a database) and you need to be able to translate the value back into the symbol, there's a mashup of both approaches

COMMODITY_TYPE = {
  currency: 1,
  investment: 2,
}

def commodity_type_string(value)
  COMMODITY_TYPE.key(value)
end

COMMODITY_TYPE[:currency]

This approach inspired by andrew-grimm's answer https://stackoverflow.com/a/5332950/13468

I'd also recommend reading through the rest of the answers here since there are a lot of ways to solve this and it really boils down to what it is about the other language's enum that you care about

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

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