Built-in equivalent to C#/Java/Python/TypeScript enums?

Hey Ruby folks,

tl;dr: Is there a simple way to emulate a built-in Enum type?

To emulate a true enum, the recommended approach seems to be having a
class with static fields (is it?):

class DirectionA
    Unknown = 0
    Horizontal = 1
    Vertical = 2

puts DirectionA::Horizontal # 1

But, having to manually specify numbers for those fields is a pain. Two
ways I’ve seen of getting around it are:

  1. Auto-incrementing counter:

    class DirectionB
    enumCount = -1
    Unknown = enumCount += 1
    Horizontal = enumCount += 1
    Vertical = enumCount += 1

    puts DirectionB::Horizontal # 1

  2. New hash instances:

    class DirectionC
    Unknown = {}
    Horizontal = {}
    Vertical = {}

    puts DirectionC::Horizontal # {}

Are any of these “standard”, or is there a better version?

Context: I’m working on a meta-syntax called GLS that compiles into
other languages. Lines of code in this syntax are compiled into their
equivalents in other languages. Lines don’t have awareness of other
lines, so there’s no way to auto-assign values to these enums in Ruby
the way there is in every other language GLS supports.

Making it output some auto-generation Enum class would be a lot of ugly


Do you need to have associated your enums with a value? In many cases a
Symbol would be used where in other languages an enum is needed. Of
course you don’t have any kind of type safety with this approach (but
you don’t have it with other types either).

If type safety is important, have a look at this Gem:

GitHub - mezuka/enum: Safe Ruby Enum implementation