From: Sean O'Dell Date: 2004-06-06T14:30:35+09:00 Subject: Re: How to ducktype a Hash? On Saturday 05 June 2004 21:35, Gavin Sinclair wrote: > On Sunday, June 6, 2004, 10:30:29 AM, Sean wrote: > >> 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. 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. > > Well, that's like static typing, which is a kludge to many people. > The "problem" is that Ruby allows you to decide on the level of > type-/class-checking that you want. No it's not. Static typing is done at load/compile time. I'm not asking for static typing, just an id on objects that implement certain interfaces. Those id's can become valid and invalid dynamically, as methods are added/removed/changed. It depends on how it's implemented. > If this were a static OO language (take Java for example) then you > would have to declare your method as taking a Map parameter, and it > sounds exactly like what you want. Then any piece of code that called > your method would need to ensure it was passing a Map. All that's > doing is "tagging all objects that I know in advance to be map-like, > and looking for that tag at that particular point in your code". The > difference is that the compiler is doing the checking, and the objects > are marked from the outset because they implement a certain interface. The tag could be a complete lie as far as I'm concerned. I'm not that picky about the compiler/interpreter actually checking the object to test that it properly implements an interface. Just having the object be able to say "I am a hash interface" would be enough. Of course, if actually implemented, I'm sure the design WOULD check for compliance, but I don't really care. Static typing is not what I want. > So if interfaces is what you want, then use them. If the fact that > you have to do the work rather than the language makes it a kludge, > then so be it. But Ruby's getting along fine without taking the > narrow road. It's not a narrow road, it's the road that offers more flexibility and is harder. It wouldn't affect the current functionality of Ruby one bit. Sean O'Dell