From: mark sparshatt Date: 2005-05-03T02:49:45+09:00 Subject: Re: enum in ruby ? 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 > The following is a simple implementation of what you want class Class def const_def(*symbols) symbols.each_with_index do |symbol, index| const_set(symbol, index + 1) end end end class MyClass const_def :CONST_A1, :CONST_A2, :CONST_A3 p CONST_A1, CONST_A2, CONST_A3 end #=> 1 2 3 HTH -- Mark Sparshatt