Ruby中类似Java的高级枚举 [英] Advanced Java-like enums in Ruby

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

问题描述

首先,这不是 Ruby中的枚举的复制品:)

First of all, this is not a duplicate of Enums in Ruby :)

该问题的公认答案表明,这是表示Ruby中枚举的好方法:

The accepted answer of that question suggests this as a good way to represent enums in Ruby:

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

在Java中,可以将多个值和方法附加到枚举值。我想在Ruby中实现相同或相似的东西。

In Java it is possible to attach multiple values and methods to an enum value. I want to achive the same or something similar in Ruby.

代表该Java枚举的最类似于Ruby的方式是什么:

What would be the most Ruby-like way to represent this Java enum:

public enum Enum

    VALUE_1("Value 1"),
    VALUE_2("Value 2"),
    VALUE_3("Value 3");

    Enum(String value) {
        this.value = value;
    }
    public String getValue() {
        return value;
    }
    private String value;
}  

编辑:

我还想保留Java枚举的隐式功能:

I also want to keep the implicit features of Java enums:


  • ...检索序数值

  • ...对枚举值(或等效值)的调用方法

示例:

Enum.VALUE_1.getValue(); // "Value 1"
Enum.VALUE_2.name();     // "VALUE_2"
Enum.VALUE_3.ordinal();  // 2


推荐答案

class MyEnum
  attr_accessor :value
  def initialize(value)
    @value = value
  end

  VALUE1 = new("Value 1")
  VALUE2 = new("Value 2")

  class << self
    private :new
  end
end

MyEnum::VALUE2 # Enum with value "Value 2"
MyEnum.new # Error

更精细的解决方案,它允许您定义任意的枚举类,并且还为您提供 ordinal()

A more elaborate solution that allows you to define arbitrary "enum classes" and also gives you ordinal():

def enum(*values, &class_body)
  Class.new( Class.new(&class_body) ) do
    attr_reader :ordinal

    def initialize(ordinal, *args, &blk)
      super(*args, &blk)
      @ordinal = ordinal
    end

    values.each_with_index do |(name, *parameters), i|
      const_set(name, new(i, *parameters))
    end

    class <<self
      private :new
    end
  end
end

# Usage:
MyEnum = enum([:VALUE1, "Value 1"], [:VALUE2, "Value 2"]) do
  attr_reader :str
  def initialize(str)
    @str = str
  end
end

MyEnum::VALUE1.str #=> "Value 1"
MyEnum::VALUE2.ordinal #=> 1

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

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