From: Garance A Drosehn Date: 2006-03-19T09:01:57+09:00 Subject: Re: c/c++ enum equivalent? On 3/17/06, benjohn@fysh.org wrote: > > I'd like to fill a module with valueless constants (because I don't care > about the actual values, just that they are unique, and named) # -------+---------+---------+-------- + --------+---------+---------+---------+ # Add methods enum and bit_enum to the Object class, thus making it much # easier and less error-prone to define a long list of constants in a # class. This idea comes from Ara.T.Howard@noaa, in a posting to ruby-talk # on August 2, 2005 (in reply to a question). These work very nicely with # a word-list array as generated via %w(). Very clever! # class Object def enum_constants(*list) mc = Module === self ? self : self.class list.flatten.each_with_index{|e, i| mc.const_set e.to_s.intern, i} end def enum_bit_constants(*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 # -------+---------+---------+-------- + --------+---------+---------+---------+ An example of use: # Constants that define all categories of packets which we recognize. enum_constants %w( SBC_NONE SBC_ARRAY SBC_GOODPW SBC_GOODKEY SBC_GOODNONE SBC_BADPW SBC_BADKEY SBC_BADNONE SBC_IGNFAIL SBC_ALL SBC_UNMATCHED ) # "UNMATCHED" should be the last one. SBC_ENUMCOUNT = SBC_UNMATCHED + 1; I've been meaning to add a few more bells and whistles to this, such as having a way for 'enum_constants' to automatically handle the definition of values such as SBC_ENUMCOUNT. But of course I have a few million things that "I've been meaning to do", and never get around to. Someone else had a module of some sort for enums. I forget who, but it was someone on this mailing list in the last month or so. Their version was very different from the above, and it in some situations what they did would have some significant advantages over the simple solution I like to use. -- Garance Alistair Drosehn = drosihn@gmail.com Senior Systems Programmer or gad@FreeBSD.org Rensselaer Polytechnic Institute; Troy, NY; USA