From: Clemens Hintze Date: 2001-01-05T10:40:02+09:00 Subject: [ruby-talk:8659] Re: Any way to get enumerated values? --Multipart_Fri_Jan__5_02:21:38_2001-1 Content-Type: text/plain; charset=US-ASCII >>>>> "Lyle" == Lyle Johnson 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 = mod =3D Module.new name, value =3D "", -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} =3D #{value}" end if arg.type =3D=3D String name, value =3D arg, value + 1 elsif arg.type =3D=3D Symbol name, value =3D arg.id2name, value + 1 elsif arg.type <=3D Numeric mod.module_eval "remove_const :#{name}" value =3D arg else raise TypeError, "only String, Symbol or Numeric instances allowed"= , caller[2..-1] end end mod end if __FILE__ =3D=3D $0 # Gnark =3D> 2 # Blubb =3D> 7 # Foo =3D> 8 # Bar =3D> 9 # Foobar =3D> 10 spam =3D Enumeration("Gnark",2, "Blubb",7, "Foo", :Bar, :Foobar) = print "Value of spam::Gnark =3D> ", spam::Gnark, "\n" print "Value of spam::Bar =3D> ", 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--