Advanced Java-like enums in Ruby

后端 未结 3 2122
梦毁少年i
梦毁少年i 2021-02-02 03:04

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

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

cl         


        
3条回答
  •  春和景丽
    2021-02-02 03:33

    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
    

    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 < "Value 1"
    MyEnum::VALUE2.ordinal #=> 1
    

提交回复
热议问题