From: Sam Roberts Date: 2005-01-27T11:05:59+09:00 Subject: Re: Injecting methods from one class into another. Quoteing dblack@wobblini.net, on Wed, Jan 26, 2005 at 11:22:33PM +0900: > >>>Duck typing, essentially, means that, /in a particular context/, a > >>>given object has all the characteristics of a given type. For example, > >>>it might be enough for an object to implement [] and []= for it to be > >>>treated as a Hash in a certain context. > >> > >>It's not exactly that it's being treated as a Hash -- it's more that, > >>*like* a Hash, it's being treated as an object that responds to [] and > >>[]=. This is, perhaps, a subtle point, but I think it's key in > >>getting away from the class-based view. All of the []/[]= objects > >>converge on the type that can only be described as "the type of > >>objects that respond to [] and []=". In that sense, Hashes are just > >>one of infinitely many possible objects that exhibit the behaviors of > >>that type. > > > >I see your point. > > > >However, if it responds to []= in a way that is NOT like a Hash responds > >to those methods, it aint ducky type like a Hash. > > Do you mean how many arguments it takes? Beyond that, one object's > behavior on being sent the []= message doesn't have to resemble > another object's, from the point of view of type. The main thing is > that they can both handle the message (including arguments). and what they do with those args. > Actually this is an area where people have pointed to a potential > limitation or even pitfall of duck typing: namely, coincidence of > method name where there really is no common ground -- something like: > > dog.bark # ask dog object to bark > tree.bark # retrive bark attribute of tree > > On the other hand, I'm not sure there have been any real-world reports > of things like this causing problems. How about #each? Almost every class has one - I'm not sure that thinking of "the type of objects that respond to #each" will get you very far in Ruby! > And a lot of duck typing ends up dealing with cases where at least > loose conventional expectations apply (like [] and []= being > index-ish, and << being append-ish). [] with Bignum, Array, and Hash are all indexish, and calling an API expecting a Hash of values (String => value) as an arg with a Bignum will not work well! On the other hand, a DB table that maps String to values might very well work, because it's [] is more like a Hash, and less like a Bignum. So, I guess I don't understand your point. Knowing a class responds to a method, particularly the common method names like #each and #[] doesn't seem to tell you much about the interface, really. Interface is more than syntax, the semantics are pretty important, IMHO. Cheers, Sam p.s. Even Continuation has []! It's the same as #call(). I just learned that now.