From: "David A. Black" Date: 2005-08-26T01:33:59+09:00 Subject: Re: idea: klass.from_s(str) Hi -- On Fri, 26 Aug 2005, Eric Mahurin wrote: > I wrote: >> >> 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. > > > Maybe for many of the core classes, there should be both forms > if you are going from one core class to another. I still prefer the technique of asking an object to provide, if possible, a conversion of itself. > The ugliness I think is when you are dealing with an arbitrary > class. You typically come up with an abbreviation for the > class and make a String#to_ method convert a string to > an object of that class. You could have collisions with > another class using the same name. Is that a widespread technique? (I don't believe I've ever done it.) If you do it, you'd want to do it more safely, perhaps by extending individual objects. > 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. In both of these cases: String.to_i Integer.from_s(str) you're depending on class membership and a close class/type correspondence at the level of the core classes. It's not even really the kind of scenario that duck typing pertains to. If you want to be utterly doctrinaire about never acknowledging the existence of any class, then you have to avoid *all* of this; you can't just convert in the abstract. But I believe the conversion methods have proven their usefulness, and their ability to exist peacefully in a quasi-prototype-based environment. Conversion based more closely on that quasi-prototype ideal is actually handled by extending objects, module-wise or method by method. In other words, if you want to convert obj into "an object that can do ", then you add the x capability to obj. That's fine, but it's not the same as any version of the hard-coded (as to class) things we've been talking about. David -- David A. Black dblack@wobblini.net