From: "Ara.T.Howard" Date: 2005-06-10T23:00:03+09:00 Subject: Re: duck-typing allows deeper polymorphism On Fri, 10 Jun 2005, Eric Mahurin wrote: i've had many of the same thoughts and tried to address them as simply as possible in my parseargs module > To get maximum benefit from duck-typing, several things will > help out: > > * For every duck-typed argument, document what the duck-type is - what > methods it needs to respond to and what the duck-type requirements are on > those method arguments and return values. To help out with this it would be > nice if we had something in rdoc for this - but I don't know what. this shows, right up front in the method, that the method takes an argument 'x' which must respond to 'upcase', and 'downcase'. an exception is thrown if something that does not respond to both these methods is passed in: harp:~ > cat a.rb require 'parseargs' include ParseArgs def method(*argv) pa = parseargs(argv){ arg :x, :ducktype => %w(upcase downcase) } p pa.x.upcase.downcase end method '42' harp:~ > ruby a.rb "42" note that this could be parsed via rdoc quite easily. > * A convenient way to create objects on-the-fly for duck-typed > arguments. Some implementations were given in the thread > "making a duck". two ways exist to do this easily using parseargs: * coerce the object into another type harp:~ > cat a.rb require 'parseargs' include ParseArgs def method(*argv) pa = parseargs(argv){ ra :x, :ducktype => %w(upcase downcase), 'coerce' => 'to_s' } p pa.x.upcase.downcase end method 42.0 harp:~ > ruby a.rb "42.0" * 'convince' the object that it can behave like a duck by extending on the fly harp:~ > cat a.rb require 'parseargs' include ParseArgs def method(*argv) pa = parseargs(argv){ ra :x, :ducktype => %w(upcase downcase), :convince => lambda{|obj| class << obj def upcase; '42'; end def downcase; '42'; end end } } p pa.x.upcase.downcase end method Object::new harp:~ > ruby a.rb "42" or via a module which should extend the object on the fly for increased duck-i-ness: harp:~ > cat a.rb require 'parseargs' include ParseArgs module Ducky def upcase; '42'; end def downcase; '42'; end end def method(*argv) pa = parseargs(argv){ ra :x, :ducktype => %w(upcase downcase), :convince => Ducky } p pa.x.upcase.downcase end method Object::new harp:~ > ruby a.rb "42" > * Use duck-typing everywhere! hear hear! cheers. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | My religion is very simple. My religion is kindness. | --Tenzin Gyatso ===============================================================================