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
end
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:
-
Auto-incrementing counter:
class DirectionB
enumCount = -1
Unknown = enumCount += 1
Horizontal = enumCount += 1
Vertical = enumCount += 1
endputs DirectionB::Horizontal # 1
-
New hash instances:
class DirectionC
Unknown = {}
Horizontal = {}
Vertical = {}
endputs 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
code.
Thanks!
-Josh