From: Patrick Hurley Date: 2005-08-03T04:32:22+09:00 Subject: Re: enum collection of constant values On 8/2/05, Ara.T.Howard wrote: > On Wed, 3 Aug 2005, Garance A Drosehn wrote: > > I'd like to have a set of constants for a class, where their values > > need to be unique, and preferably compact. For instance: > class methods are your friend > > snip nice Enum module I like the Enum module, but if I include it into the 'main' scope, I need to self.class.enum to make it work. A bit more brute force, but works "automatically" in all contexts would be overloading Object. This then requires a smarter method of setting the const based upon where it is called from. class Object def const_setter set = if self.respond_to? :const_set lambda { |sym, val| self.const_set sym.to_s.intern, val } elsif self.class.respond_to? :const_set lambda { |sym, val| self.class.const_set sym.to_s.intern, val } else # I don't think this code would ever get called... lambda { |sym, val| eval "#{sym} = #{val}" } end end def enum(*syms) set = const_setter syms.each_with_index do |sym,index| set.call sym, index end end def binary_enum(*syms) set = const_setter syms.each_with_index do |sym,index| set.call sym, 2 ** index end end end