From: "David A. Black" Date: 2005-08-26T00:36:35+09:00 Subject: Re: idea: klass.from_s(str) Hi -- On Thu, 25 Aug 2005, Eric Mahurin wrote: > I was thinking how in seems a little asymmetric that many > classes have #to_s method, but when you want to make one of > those objects from a String, you have to clutter the String > class with yet another #to_* method. So the String class gets > the burden of all those #to_* methods. I don't see that as a burden. It seems to correspond precisely to what's happening. > Instead, what if we > would have the convention that creating an object from a string > would be a class method (for the class of that object) instead > of another String#to_* method. So, instead of these: > > String#to_i > String#to_f > String#to_sym > String#to_ # where c is a abbreviation for the class > > you'd have these: > > Integer.from_s(str) > Float.from_s(str) > Symbol.from_s(str) > klass.from_s(str) That seems like at least an equal amount of clutter -- actually more, since you've now got a receiver, method, and argument, where the argument and the method name contain the same information (String-hood in this case). It also introduces a whole range of scenarios involving wrong arguments. I prefer simply sending a conversion request to an object and getting its response. > Maybe you'd even want to be able to convert from an inspect > string: > > klass.from_inspect(str) > > I'm not saying that we should replace all obj.to_ methods with > klass.from_ methods. I'm just saying to make them come in > pairs. If you have a klass#to_* method, you should have a > corresponding klass.from_* method if appropriate. This would > make your class more encapsulated, instead of having some of it > in String (or whatever class you are converting from). So you'd have: Integer.from_f(1.0) Integer.from_s("1") Integer.from_nil(nil) Integer.from_i(1) instead of 1.0.to_i "1".to_i nil.to_i 1.to_i I'm afraid it seems circuitous and verbose to me. David -- David A. Black dblack@wobblini.net