From: Eric Mahurin Date: 2005-09-08T02:09:32+09:00 Subject: Re: Lexical Casts with Ruby --- Paul Brannan wrote: > On Sun, Sep 04, 2005 at 12:16:26AM +0900, R??diger 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 attribute > > type can only be determined at runtime. > > > > Is there a way for lexical casts between types in Ruby? > Something like > > convert("10", Fixnum) > > => 10 > > In C++, boost::lexical_cast uses streams to convert the > object to a > string and then from the string to the desired type. > > It is easy to do the first part in ruby; all objects have a > to_s method. > > The second part is harder. There is no uniform mechanism for > converting > a string into an object. A while back, I suggested adding some klass.from_* methods. For example: def Integer.from_s(s) s.to_i; end Any class that could make one of its objects from a String would put this method in. You could do the same for other classes to convert from also: from_i, from_f, etc. Here would be the usage: Integer.from_s("10") # 10 10.to_s # "10" - nothing new As a convienence you could also add this: class String def to(klass) klass.from_s(self) end def self.from(obj) obj.to_s end end so you could do: "10".to(Integer) # 10 String.from(10) # "10" If this is a good solution for you, maybe an RCR for this more general conversion mechanism is in order. ______________________________________________________ Click here to donate to the Hurricane Katrina relief effort. http://store.yahoo.com/redcross-donate3/