On 7/20/07, Sasa [email protected] wrote:
NAME3 = 2
#etc…
end
end
end
What is more elegant way to do this? Basically, I want to convert the
numerical value to string representation (ideally via identifier name).
In ruby we often use symbols in place of of enumerations. Any place
you’d
use NAME0, use :name0. For NAME1 use :name1, etc.
For example:
class MyClass
def something
case @enum_value
when :name0
puts “In name zero mode”
when :name1
puts “In name one mode”
end
end
end
:name0.to_s #=> “name0”
If, for whatever reason you don’t want to use symbols, a way I
occasionally
use to emulate enums is the following:
NAME0 = Object.new
def NAME0.to_s
“NAME0”
end
NAME1 = Object.new
def NAME1.to_s
“NAME1”
end
…
Another method that could be used to simplify your existing code is to
use a
hash:
NAME0 = 0
NAME1 = 1
NAME2 = 2
Names = { NAME0 => “NAME0”, NAME1 => “NAME1”, NAME2 => “NAME2” }
def self.to_s(something)
Names[something]
end
You can even wrap this one up (or the previous method with some
metaprogramming:)
def self.enum(*args)
const_set(“Names”, {})
args.each_with_index do |v, i|
Names[i] = v
const_set(v, i)
end
end
enum “NAME0”, “NAME1”, “NAME2”
Thanks in advance,