rubyenums

How to implement Enums in Ruby?


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.


Solution

  • 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