From: "David A. Black" Date: 2005-09-04T00:35:37+09:00 Subject: Re: Lexical Casts with Ruby --8323328-1020658632-1125761734=:19128 Content-Type: MULTIPART/MIXED; BOUNDARY="8323328-1020658632-1125761734=:19128" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --8323328-1020658632-1125761734=:19128 Content-Type: TEXT/PLAIN; charset=X-UNKNOWN; format=flowed Content-Transfer-Encoding: QUOTED-PRINTABLE Hi -- On Sun, 4 Sep 2005, [utf-8] R=C3=BCdiger Sonderfeld wrote: > Hello, > I want to assign some values I recive in string form to attributes of a > user specified class. The problem is that I have to lexical cast the > strings into the required type. I can't use to_i or to_f because the attr= ibute > type can only be determined at runtime. > > Is there a way for lexical casts between types in Ruby? Something like > convert("10", Fixnum) > =3D> 10 See Robert's answer. Also, another possibility would be to put the knowledge directly in the object: class MyClass def x=3D(s) @x =3D s.to_i end def y=3D(s) @y =3D s.to_f end # ... end That way, you can just do: obj.x =3D "10" and have the conversion be encapsulated in the object. If using the assignment syntax seems *too* transparent (since you're not really setting it to "10"), you could use differently-named methods. But the principle would be the same: put the knowledge in the object. David --=20 David A. Black dblack@wobblini.net --8323328-1020658632-1125761734=:19128-- --8323328-1020658632-1125761734=:19128--