On Sun, 21 Oct 2001, Avdi B. Grimm wrote:
> does anyone have a ruby module that emulates C enums, so that if you
> want a bunch of uniquely-enumerated constants you can just say something
> like:
> enum( :FOO => 1, :BAR, :BAZ, :BUZ )
> ...? I thought I saw something like this awhile ago, but maybe I was
> mistaken...  it should be trivial to implement; but I didn't want to
> code it if someone else already had.

RubyX11 0.5 has X11/Type.rb
MetaRuby 0.7 has Type.rb

(in the latest (non-release) versions of those, both files are identical)

Type.rb defines several things, among which there is ChoiceType. You can
do:

Blah = ChoiceType.new( :FOO, :BAR, :BAZ, :BUZ )

and it will consider the set of those four symbols, mapped to the
integers 0..3, as a type called Blah, so you can then do stuff like:

case x
when Blah; ...
end

and you can do conversions from the Symbol to the Integer and back
(on average, use the Symbols in Ruby, and convert to Integer when you need
to pass it over a binary-protocol...)

Ruby does not notify objects when they get assigned to constants, so if
you want the typename to print you may wish to do this yourself:

Blah.const_name_is Blah, Module.nesting

(or something like that)

If you want the thing to start at 1, you can do:

Blah = ChoiceType.new( nil, :FOO, :BAR, :BAZ, :BUZ )

but then nil is now part of your type. Now if you really want to start it
at 1, you can do (using the line without nil):

Blah.base = 1

but the .base feature is going away now, replaced by:

Blah = ChoiceType.new({
	:FOO => 1,
	:BAR => 2,
	:BAZ => 3,
	:BUZ => 4,
})

________________________________________________________________
Mathieu Bouchard                   http://hostname.2y.net/~matju