From: Robert Klemme Date: 2005-09-04T00:25:28+09:00 Subject: Re: Lexical Casts with Ruby 2005/9/3, R�diger Sonderfeld : > 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 Well, there are several options: You can use send, like your_string.send(:to_i) where you determine the symbol (:to_i, :to_f etc) at runtime. You can use case result = case your_string when /^\d+$/ then your_string.to_i when /^\d.\.\d+/ then your_string.to_f else your_string end Or you put conversions into a map conv = { Fixnum => lambda {|x| x.to_i}, Float => lambda {|x| x.to_f}, } result = conv[Fixnum][your_string] Hope, that gets you started. Kind regards robert