eugene_trebin
eugene_trebin

Reputation: 1553

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

I need to get string name of enum state by integer value, and i do it next way

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

Does anybody know better way to do it?

enum state: {
         created: 0,
         cancelled: 100,
         complete: 10,
       }

Upvotes: 15

Views: 12658

Answers (2)

Dty
Dty

Reputation: 12273

Here's a solution that removes the magic number.

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

Upvotes: 5

eugene_trebin
eugene_trebin

Reputation: 1553

Order.states.key(100) => 'cancelled'

Upvotes: 33

Related Questions