enumeration with symbol name information

S

Sasa

Hello everybody...
I have a beginne's question:

I've created class for my numeric constants, it looks like:

class MyClass

NAME1 = 0
NAME2 = 1
NAME3 = 2
#etc...

def self.to_s(something)
case something
when 0
"NAME1"
when 1
"NAME2"
when 2
"NAME3"
#etc...
end
end

end


What is more elegant way to do this? Basically, I want to convert the
numerical value to string representation (ideally via identifier name).

Thanks in advance,
Sasa
 
M

Mariusz Pękala

--7JfCtLOvnd9MIVvH
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

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--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top