From: "Hal E. Fulton" Date: 2003-08-09T04:33:26+09:00 Subject: Re: Ducktype, right? ----- Original Message ----- From: "Ben Giddings" To: "ruby-talk ML" Sent: Friday, August 08, 2003 12:51 PM Subject: Re: Ducktype, right? > On Fri August 8 2003 1:25 pm, Dave Thomas wrote: > > fred << "dog" > > > > in Ruby, I don't care whether fred is a String, a File, or an Array (a > > fact that's very useful when writing unit tests). > > The one thing that I think is underemphasized about the duck typing concept is > that just because something floats, it might not be a duck (it might be a > witch!) Who are you, who are so wise in the ways of science? ;) > In Java you could check to see if something is of a certain class, but what > was more often done was to see if something implemented a certain interface. > Implementing an interface was a way of signalling "I declare myself to act > like a duck". And the fact you implemented the interface meant that you had > all the necessary features to act like a duck. You weren't allowed to > implement the interface and then only choose certain duck-like features. > > It seems to me that duck-typing in Ruby should strive for the same thing. > Checking for one method isn't enough, in my opinion. Actually, I've often thought the same thing. respond_to? is good enough in many/most cases. Sometimes it is not. Example: << is usually an append operation. You can happily apply it to a string, an array, or a file. But a Fixnum also responds to that method... meaning "left shift." If the methods are collected in a module with a canonical name, that improves the situation. if x.is_a? Enumerable then... But I'm not sure I'd recommend encasing methods in a bunch of new modules like Appendable. Though it is an idea... Hal -- Hal Fulton hal9000@hypermetrics.com