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.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Two ways. Symbols (
:foonotation) or constants (FOOnotation).Symbols are appropriate when you want to enhance readability without littering code with literal strings.
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.
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
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