From: Eric Mahurin Date: 2005-08-26T02:11:22+09:00 Subject: Re: idea: klass.from_s(str) --- "David A. Black" wrote: > > The klass.from_s(str) form also offers a little more power. > If > > you are dealing with an arbitrary class (possibly of > another > > object) and you want to convert a String to an object of > that > > class, you just call the from_s method of that class. You > > don't have to go figure out what the right String#to_* > method > > to call is based on the class (and violate duck typing). > > Duck typing is irrelevant here. I think an example is needed to demonstrate my point. Say you have a command line parser where you want to convert options from String to the relavent class. Somewhere in the specification, you may specify the class that you want the option to be. With the String#to_* methods, you have to do something like this: def parse_option(klass,option) if klass.equal?(String) option elsif klass.equal?(Integer) option.to_i elsif klass.equal?(Float) option.to_f else raise("can't convert #{option} to #{klass}") end end With klass.from_s(str) methods, here is what you get: def parse_option(klass,option) klass.from_s(option) end Which is duck-typed? And like I said, in another message, we can still have this to add more convienence: class String def to(klass) klass.from_s(self) end end ____________________________________________________ Start your day with Yahoo! - make it your home page http://www.yahoo.com/r/hs