Advanced Java-like enums in Ruby

后端 未结 3 2090
梦毁少年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:39

    You can always create a system that's like the Java version:

    module Foo
      class Value
        attr_reader :value
    
        def initialize(value)
          # Save a frozen, immutable copy
          @value = value.dup.freeze
        end
    
        # Patch in methods to make it appear more friendly and string-like
        alias_method :to_s, :value
        alias_method :inspect, :value
      end
    
      # Define constants
      BAR = Value.new('bar')
      BAZ = Value.new('baz')
      BIZ = Value.new('biz')
    end
    
    puts Foo::BAR
    # => bar
    

提交回复
热议问题