From: Logan Capaldo Date: 2007-07-20T19:35:23+09:00 Subject: Re: enumeration with symbol name information ------=_Part_63405_29994599.1184927725916 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 7/20/07, Sasa wrote: > > Hello everybody... > I have a beginne's question: > > I've created class for my numeric constants, it looks like: > > class MyClass > > NAME1 = 0 > NAME2 = 1 > NAME3 = 2 > #etc... > > def self.to_s(something) > case something > when 0 > "NAME1" > when 1 > "NAME2" > when 2 > "NAME3" > #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, > Sasa > > > > ------=_Part_63405_29994599.1184927725916--