From: Lloyd Zusman Date: 2004-06-06T10:25:56+09:00 Subject: Re: How to ducktype a Hash? "Sean O'Dell" writes: > On Saturday 05 June 2004 15:01, John W. Long wrote: >> >why do you need to say 'it is hash like' ? >> >Wo'nt it be easyer to say 'I need this methods, so I'll just check >> >them' ? >> > >> >BTW, probably the simpler solution is : >> > >> >x.methods =={}.methods >> >> This is even worse than object.kind_of(Hash). The whole point of "duck >> typing" (as I understand it) is that you don't check if an object has >> certain methods. You just use them. Ruby will throw an error if there's >> a problem. > > Which always sounded fine to me until I was actually exposed to this kind of > "typing." The problem is, the methods [] and []= are there, they just don't > do what I need them to do. Duck typing completely and utterly don't help, > and Ruby has no way to tell me when an object's [] and []= are hash-like or > something else. I, for one, totally agree with you. Duck typing cannot work unless methods with the same names and signatures behave in the same way in the various classes that implement them. If the ability to do duck typing is deemed to be an important and necessary feature of an object-oriented language, then the standard libraries that are written for that language _must_ provide different names and/or signatures for methods that perform different functions. Since [] and []= have certain semantics for one set of classes (array-like classes) and different semantics for other classes (hash-like classes), then we must conclude that Ruby was not designed with the duck typing in mind. Therefore, the best we can say about the current implementation of Ruby is that duck typing can be used in _some_ cases, but not all. I'm not trying to say that this is a deficiency of Ruby. On the contrary; my point here is that I think that Ruby is a very well designed language. On the other hand, I believe that duck typing should not be treated as the be-all and end-all for type checking in Ruby, given that Ruby's standard libraries do not seem to have been designed with duck typing in mind. > [ ... ] My solution is going to end being something like "tagging all > objects that I know in advance to be hash-like, and then looking for > that tag at that particular point in my code." That's a kludge to me. -- Lloyd Zusman ljz@asfast.com God bless you.