On 02/08/05, Garance A Drosehn <drosihn / gmail.com> 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:
>    SB_NONE = 0; SB_GOOD = 1; SB_BAD = 2; SB_LOGIC_ERR = 3;
>    SB_MAX = SB_LOGIC_ERR
> 
> but if I want to modify this list by adding something in the middle,
> then I have to remember to increment (by hand) all the values
> which come after that new value.
> 
> In C, I would do something like:
>     typedef enum { SB_NONE, SB_GOOD, SB_BAD,
>         SB_LOGICERR } sb_set;
> 
> Looking through the pickaxe book, it looks like the closest thing
> I can do is to create an array of words, and then use the indexes
> of where those words are in the array.  But that isn't really the
> same thing.   I'd like the efficiency of having constant values,
> which would be referred to by name.
> 
> (And after I have that for a compact set of values, I'd want a
> similar feature which would give me a bit-wise unique set of
> values.  Eg:  SB_MODA = 1; SB_MODB = 2; SB_MODC = 4;
> SB_MODD = 8; -- such that I could combine the values together
> using '|', and tell which values were 'or'-ed together to get that
> combined value...)
> 
> --
> Garance Alistair Drosehn     =             drosihn / gmail.com
> Senior Systems Programmer               or   gad / FreeBSD.org
> Rensselaer Polytechnic Institute;             Troy, NY;  USA
> 
> 

Metaprogramming is your friend:

bschroed@black:~/svn/projekte/ruby-things$ cat enum.rb 
class Object
  def self.enums(*args)    
    args.flatten.each_with_index do | const, i |
      class_eval %(#{const} = #{i})
    end
  end
  
  def self.bitwise_enums(*args)    
    args.flatten.each_with_index do | const, i |
      class_eval %(#{const} = #{2**i})
    end
  end
end


class Foo
  enums %w(FOO BAR BAZ)
  bitwise_enums %w(ONE TWO FOUR EIGHT)
end

p [Foo::FOO, Foo::BAR, Foo::BAZ]
p [Foo::ONE, Foo::TWO, Foo::FOUR, Foo::EIGHT]
bschroed@black:~/svn/projekte/ruby-things$ ruby enum.rb 
[0, 1, 2]
[1, 2, 4, 8]

regards,

Brian

-- 
http://ruby.brian-schroeder.de/

Stringed instrument chords: http://chordlist.brian-schroeder.de/