From: Alex Young Date: 2006-07-24T19:57:19+09:00 Subject: Re: I'll have the duck! Robert Dober wrote: > On 7/24/06, Alex Young wrote: > >> >> Robert Dober wrote: >> > On 7/24/06, transfire@gmail.com wrote: >> >> >> and hence any hash-like object. >> > >> > Yeah great, you see that is what troubles me, it is completely cool to >> talk >> > about hash-like object, but what is a hash-like object? Which messages >> > must >> > a hash-like object respond to? All of Hash, I suppose, thus a subclass, >> or >> > only some, then we can talk about protocols again, but the failure >> to be >> > able to define the protocol just worries me. >> That's the whole point. Duck-typing means that your class only needs to >> define the methods (of Hash, in this case) that the called method >> (transform here) needs, *not* the whole Hash class, *without* having to >> specify a protocol. If you want to specify a protocol, there's one >> example of how to do it here: >> >> http://www.erikveen.dds.nl/monitorfunctions/index.html#6.0.0 > > > > Well I have read that, kind of, it is a little bit heavy, too heavy I am > afraid. > I still do not get the point, are you saying I am right (let dogs life) or > are you saying I am wrong (let only ducks life). It's my opinion that opposition to duck-typing is a bad idea (especially when dealing with Ruby, given how pervasive it is), but that doesn't make it wrong. It is perfectly possible for both dogs and ducks to co-exist. > Mixins are another nice way to think about it > > class Dog > include Duck > ... # no this is *not* the Perl6 Thingy Jabbawalky operator ;) > end > > d = Puppet > d.implements? Duck ==> true If you're always supplying Duck's functionality as a mixin, you can do: Duck === d => true The beauty of duck-typing is that you don't have to, though. If you wanted an Object#implements? method which doesn't rely on implementation via mixin, you could do it like this: class Object def implements?(module) my_methods = Set.new(self.public_methods) module_methods = Set.new(module.instance_methods) return my_methods.superset?(module_methods) end end Again, that misses the point somewhat, though - duck-typing lets you not have to think about the concept of a defined interface (in the Module sense, at least). If your method only calls #foobar on a passed object, then that object only need respond to the #foobar method. > but maybe this is here already, gotta check. > Thx for your considerations > I repeat nevertheless > Ducks are great, unless they kill Dogs ;) You can always check the class of an object, and there are ways to make the syntax less cumbersome than it might otherwise be. -- Alex