From: "Mariusz Pękala" Date: 2007-07-20T20:18:13+09:00 Subject: Re: enumeration with symbol name information --7JfCtLOvnd9MIVvH Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On 2007-07-20 19:00:04 +0900 (Fri, Jul), Sasa wrote: > Hello everybody... > I have a beginne's question: >=20 > I've created class for my numeric constants, it looks like: >=20 > class MyClass >=20 > NAME1 =3D 0 > NAME2 =3D 1 > NAME3 =3D 2 > #etc... >=20 > def self.to_s(something) > case something > when 0 > "NAME1" > when 1 > "NAME2" > when 2 > "NAME3" > #etc... > end > end >=20 > end >=20 >=20 > What is more elegant way to do this? Basically, I want to convert the=20 > numerical value to string representation (ideally via identifier name). >=20 > Thanks in advance, > Sasa=20 If your numeric values always start from 0, then you may use an array: class MyClass NAMES =3D [ 'NAME1','NAME2','NAME3' ] def self.to_s(something) # personally I would rather avoid redefining cla= ss.to_s NAMES[something.to_i] || default_value end end If this is unacceptable, you may use a hash: NAMES =3D { 1 =3D> 'NAME1', 2 =3D> 'NAME2', 5 =3D> 'NAME3' } NUMBERS =3D Hash[ *NAMES.map {|k,v| [v,k]}.flatten ] # may be useful := -) def self.to_s(something) NAMES[ something ] || defaul_value end def self.to_i(something) # may be useful :-) NUMBERS[ something ] || default_number end --=20 No virus found in this outgoing message. Checked by 'grep -i virus $MESSAGE' Trust me. --7JfCtLOvnd9MIVvH Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7-ecc0.1.6 (GNU/Linux) iD8DBQFGoJnSsnU0scoWZKARAshNAJ91K4U2VSrfppKUvtTUe59rsS63dACfSoGh HxTcfQQgitzfLm29IA1hWu4= =6IoB -----END PGP SIGNATURE----- --7JfCtLOvnd9MIVvH--