From: Ara.T.Howard@... Date: 2005-05-03T03:04:34+09:00 Subject: Re: enum in ruby ? On Mon, 2 May 2005, Andreas Habel wrote: > Hi, > > I`ve a simple question about constants in ruby. Is there a possibility to > define constants in a module or a class like a enum in c? > > Maybe something short like the 'attr_accessor' syntax would be great! > > class MyClass > const_def :CONST_A1, :CONST_A2, :CONST_A3 > const_def :CONST_B1, :CONST_B2, :CONST_B3 > end > > eq. > > class MyClass > > CONST_A1 = 1 > CONST_A2 = 2 > CONST_A3 = 3 > > CONST_B1 = 1 > CONST_B2 = 2 > CONST_B3 = 3 > end harp:~ > cat a.rb class MyClass CONSTANTS = [ CONST_A1 = 1, CONST_A2 = 2, CONST_A3 = 3, CONST_B1 = 1, CONST_B2 = 2, CONST_B3 = 3, ] end p MyClass::CONST_A1 p MyClass::CONST_B2 # OR class Module def enumerate(*list) [ list ].flatten.each_with_index{|c,i| const_set "#{ c }".upcase, i + 1} end end class MyClass2 enumerate :CONST_A1, :CONST_A2, :CONST_A3 enumerate %w( CONST_B1 CONST_B2 CONST_B3 ) end p MyClass2::CONST_A1 p MyClass2::CONST_B2 harp:~ > ruby a.rb 1 2 1 2 HTH. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | renunciation is not getting rid of the things of this world, but accepting | that they pass away. --aitken roshi ===============================================================================