NAH NAH - 3 months ago 11
Ruby Question

Enums in Ruby and getting string value

I have the following module in one of my rails models:

module Color
RED = 0
BLUE = 1
YELLOW = 2
end


I store these values in a db as ints by doing
Color::RED
etc. When I retrieve the values back I want to get the string, ie "red". But I am having trouble converting 0 -> "RED"/"red". What am I missing? Can I do this with the module approach or is there a better way?

Answer

Since you cannot use Rails ActiveRecord enum, then a hash might be useful:

COLORS = { "red" => 0, "blue" => 1, "yellow" => 2 }

store a color code

red_color = COLORS["red"] #red_color = 0

convert from color code, use Hash#key method

COLORS.key(0)
# > "red"

You can even make a helper for that, something like:

def color_code_to_string(code)
  COLORS.key(code) # returning a default color in case if wrong code number is a good idea too
end
Comments