What is the best way to get an enum string name from an integer value

I need to get the string name of the state of an enumeration by an integer value, and I do it as follows

Order.states.find{|x| x[1] == data['stateId']}

Does anyone know a better way to do this?

enum state: {
         created: 0,
         cancelled: 100,
         complete: 10,
       }
+4
source share
2 answers
Order.states.key(100) => 'cancelled'
+11
source

Here is a solution that removes the magic number.

Order.states.key(Order.states[:cancelled]) => 'cancelled'
0
source

Source: https://habr.com/ru/post/1672485/


All Articles