From: "David A. Black" Date: 2005-08-26T03:43:06+09:00 Subject: Re: idea: klass.from_s(str) Hi -- On Fri, 26 Aug 2005, Eric Mahurin wrote: > --- "David A. Black" wrote: > >> On Fri, 26 Aug 2005, Eric Mahurin wrote: >> >>> 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? >> >> Neither of them would I include in, say, an essay, on duck >> typing, not >> because they "violate" it (it's not a rule) but because it's >> not >> relevant. Once you're passing class names around and doing >> explicit >> conversions based on class, that's what you're doing, and you >> might as >> well embrace it. > > I'd disagree. Even if you are passing classes around you > should be able to apply duck typing if you have the right > infrastructure. The class just has to respond to the right > methods as opposed to the object. The class *is* the object, in this case. But that's not my point. I just think there's no point in concealing the conversion code, in order to go through a kind of pseudo-polymorphic layer. > Let's make a class out of this - an option spec: > > class Option > def initialize(name,required=false,klass=String) > @name = name > @required = required > @klass = klass > end > ... > def parse_option_arg(arg) > @klass.from_s(arg) > end > end > > So, when you are describing the command line, you might give it > a list of these option specs: > > Option.new("n",true,Integer), > Option.new("ratio",true,Float), > Option.new("f",true,File), # File#from_s(str) will open a File (File.from_s?) In what mode? Or will it write the string to a file? I don't have any instinctive sense of what File.from_s would or should do. That's part of the problem for me: I don't think there should be a generalized conversion mechanism because I'm not convinced that class-to-class conversions (whether lexically visible as such, or stashed one method definition away) really are a generality. David -- David A. Black dblack@wobblini.net