--Multipart_Fri_Jan__5_02:21:38_2001-1
Content-Type: text/plain; charset=US-ASCII
>>>>> "Lyle" Lyle Johnson <ljohnson / resgen.com> writes:
(...)
Lyle> Ahhh, I didn't specify enough constraints on the problem ;)
Lyle> And those would be that the constants are in fact integer
Lyle> values; I need to be able to specify a specific starting
Lyle> value for the sequence; and I want the values to be
Lyle> generated sequentially so that I'm guaranteed that all the
Lyle> values are greater than the starting value.
Lyle> In other words, I need it to work exactly like C enums ;)
Hmmm ... in the beginning, erhm ... I mean: once upon a time ... no.
What I want to say is, that I had written such a module as experiment
some time ago!
The trick is to create an anonymous module that contains constants
with the corresponding values. You catch the reference of that module
and put it into an variable. Then you may refer to a certain enum via
the module::Constant access syntax!
I have attached my module on that article. If you simply start it via
ruby enumeration.rb
you will see some test output. I really *love* that language :-)))
(...)
HTH,
\cle
--Multipart_Fri_Jan__5_02:21:38_2001-1
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="enumeration.rb"
Content-Transfer-Encoding: quoted-printable
#!/bin/env ruby
def Enumeration(*args)
args << :sentinel od = Module.new
name, value = "", -1
for arg in args
unless name.empty?
unless name[0].between?(?A, ?Z)
raise SyntaxError, "Enumerator have to begin with [A-Z]: (#{name})",
caller[2..-1]
end
mod.module_eval "#{name} = #{value}"
end
if arg.type == String
name, value = arg, value + 1
elsif arg.type == Symbol
name, value = arg.id2name, value + 1
elsif arg.type <= Numeric
mod.module_eval "remove_const :#{name}"
value = arg
else
raise TypeError, "only String, Symbol or Numeric instances allowed",
caller[2..-1]
end
end
mod
end
if __FILE__ == $0
# Gnark => 2
# Blubb => 7
# Foo => 8
# Bar => 9
# Foobar => 10
spam = Enumeration("Gnark",2, "Blubb",7, "Foo", :Bar, :Foobar)
rint "Value of spam::Gnark => ", spam::Gnark, "\n"
print "Value of spam::Bar => ", spam::Bar, "\n"
end
--Multipart_Fri_Jan__5_02:21:38_2001-1
Content-Type: text/plain; charset=US-ASCII
--Multipart_Fri_Jan__5_02:21:38_2001-1--