From: "Ara.T.Howard" Date: 2005-08-03T04:51:45+09:00 Subject: Re: enum collection of constant values On Wed, 3 Aug 2005, Patrick Hurley wrote: > 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 hmm. this is a bit shorter harp:~ > cat a.rb class Object def enum(*list) mc = Module === self ? self : self.class list.flatten.each_with_index{|e, i| mc.const_set e.to_s.intern, i} end def bit_enum(*list) mc = Module === self ? self : self.class list.flatten.each_with_index{|e, i| mc.const_set e.to_s.intern, 2 ** i} end end class C enum %w( FOO BAR FOOBAR BARFOO ) end class B bit_enum %w( FOO BAR FOOBAR BARFOO ) end enum %w( FOO BAR ) bit_enum %w( FOOBAR BARFOO ) p C::FOO p C::BARFOO printf "0b%8.8b\n", B::FOO printf "0b%8.8b\n", B::BARFOO p FOO p BAR printf "0b%8.8b\n", FOOBAR printf "0b%8.8b\n", BARFOO harp:~ > ruby a.rb 0 3 0b00000001 0b00001000 0 1 0b00000001 0b00000010 probably could also combine this idea with the Enum module... nice mod btw. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | My religion is very simple. My religion is kindness. | --Tenzin Gyatso ===============================================================================