Yeonho Yeonho - 5 months ago 7
Ruby Question

How to get the name of the constant

module Colors
Red = 0
Blue = 1
Green = 2
end


When I have the reference to the module
Colors
, I can get the name of that module
"Colors"
by
Colors.name
.

Is it possible to get the string representation of the constant
"Colors::Red"
when I have a reference to the constant
Colors::Red
?

Answer

Yes, provided only one constant has a value equal to the value of the given reference.

def ref_to_str(color)
  k = Colors.constants.find { |k| Colors.const_get(k) == color }
  return nil unless k
  "Colors::#{k}"
end

ref_to_str(Colors::Red)
  #=> "Colors::Red" 
ref_to_str(Colors::Blue)
  #=> "Colors::Blue" 
ref_to_str(Colors::Green)
  #=> "Colors::Green"