From: "David A. Black" Date: 2005-06-07T01:57:14+09:00 Subject: Re: making a duck Hi -- On Tue, 7 Jun 2005, Eric Mahurin wrote: > Regarding duck-typing... Is there an easy way make a "duck"? > i.e. an object that responds to enough methods to be an > acceptable argument to a certain methods. For example, if I > have a method that takes aString and uses the #size and #[i] > methods, I could pass it something that looked just enough like > a String to work: > > alphabet = Object.duck(:[],proc{|i|?a+i},:size,proc{26}) > > The implementation I came up with is this: > > class Object > def self.duck(*name_proc) > duck = self.new > duckclass = (class << duck;self;end) > while not name_proc.empty? > name,proc = name_proc.slice!(0,2) > duckclass.send(:define_method,name,&proc) > end > duck > end > end > > > Is there another way to do this? With all of the talk about > duck-typing, there would already be something out there to do > this. I've always understood "duck typing" to refer to a particular approach to the handling of method calls on objects, so I personally wouldn't expect a to see a correlation between the amount of talk about duck typing and this kind of technique. Your technique looks to me like it has more to do with the opposite end of the process: the preparation and priming of an object, as a way of creating a situation favorable to subsequent duck typing. I don't think what you've got here stands in any unique or special relation to duck typing; after all, from the duck typing perspective, a method that an object got from its original Class is just as much part of the object's behavior as a method the object got extended with later. In fact... your technique actually calls to mind Module#extend. Do you have a case where you'd prefer to do it the way you've done it above, rather than defining the methods in a module and then extending your object with it? David -- David A. Black dblack@wobblini.net