# Ducktype, right?

**URL:** <https://rubytalk.org/t/ducktype-right/7297>\
**Category:** ruby-talk\
**Created:** [8 August 2003 15:33 UTC](https://rubytalk.org/t/ducktype-right/7297 "2003-08-08T15:33:17Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mills\_Thomas\_app1tam](https://avatars.discourse-cdn.com/v4/letter/m/5f9b8f/32.png) [@Mills\_Thomas\_app1tam](https://rubytalk.org/u/Mills_Thomas_app1tam)\
**Post date:** [8 August 2003 15:33 UTC](https://rubytalk.org/t/ducktype-right/7297/1 "2003-08-08T15:33:17Z")

</div>

I guess I’m not sure what duck typing is, then. My example was assuming I  
was using the original method from my first post. Thus, duckness is a list  
of ducky methods. My second example was selling myRobot to a duckHerder  
since, for all intents and purposes, myRobot acts like a duck. The  
duckHerder would also consider myRobot to be a duck, assuming we agreed on  
duckness. I thought that was duck-typing.

Drew

> **···**
>
> > -----Original Message-----  
> > From: [dblack@superlink.net](mailto:dblack@superlink.net) [[mailto:dblack@superlink.net](mailto:dblack@superlink.net)]  
> > Sent: Friday, August 08, 2003 11:00 AM  
> > To: [ruby-talk@ruby-lang.org](mailto:ruby-talk@ruby-lang.org)  
> > Subject: Re: Ducktype, right?
> > 
> > > ### in Ruby
> > > 
> > > yourRobot.quack if ducktype(yourRobot, duckness)  
> > > duckHerder.buy(myRobot) if ducktype(myRobot, duckness)
> > 
> > (I’m not sure I’d file the second example under “duck typing”  
> > (since it’s argument-checking rather than object capability  
> > checking), but you could probably come up with a method name  
> > that was a superset of both 🙂

---

<div class="post-metadata">

**Author:** ![David\_A\_Black2](https://avatars.discourse-cdn.com/v4/letter/d/57b2e6/32.png) [@David\_A\_Black2](https://rubytalk.org/u/David_A_Black2)\
**Post date:** [8 August 2003 16:32 UTC](https://rubytalk.org/t/ducktype-right/7297/2 "2003-08-08T16:32:20Z")

</div>

Hi –

> > From: [dblack@superlink.net](mailto:dblack@superlink.net) [[mailto:dblack@superlink.net](mailto:dblack@superlink.net)]  
> > Sent: Friday, August 08, 2003 11:00 AM  
> > To: [ruby-talk@ruby-lang.org](mailto:ruby-talk@ruby-lang.org)  
> > Subject: Re: Ducktype, right?
> > 
> > > ### in Ruby
> > > 
> > > yourRobot.quack if ducktype(yourRobot, duckness)  
> > > duckHerder.buy(myRobot) if ducktype(myRobot, duckness)
> > 
> > (I’m not sure I’d file the second example under “duck typing”  
> > (since it’s argument-checking rather than object capability  
> > checking), but you could probably come up with a method name  
> > that was a superset of both 🙂
> 
> I guess I’m not sure what duck typing is, then. My example was assuming I  
> was using the original method from my first post. Thus, duckness is a list  
> of ducky methods. My second example was selling myRobot to a duckHerder  
> since, for all intents and purposes, myRobot acts like a duck. The  
> duckHerder would also consider myRobot to be a duck, assuming we agreed on  
> duckness. I thought that was duck-typing.

The wisest answer would probably be: if it walks like duck typing and  
talks like duck typing, then it is duck typing 🙂 But I meant only  
that I’ve never heard the term applied to that kind of argument checking  
(where the object being checked for capabilities isn’t actually the only  
being asked to do anything).

I guess I’d tend to say that the concept of “agreeing on duckness”,  
where “duckness” is taken to be an immutable list of method names, is more  
a particular way of addressing the ambient fact of duck typing (i.e.,  
the fact that the “type” of Ruby objects is essentially inferential)  
than it is, per se, duck typing.

Actually the best way to get at this is to put the spotlight on  
something relatively unexciting-looking in your code: duckHerder.buy.  
We’ve been taking that method call for granted – but it also operates  
in the universe of duck typing. You’re assuming that, at that moment  
in its existence, the duckHerder object knows how to respond to “buy”.  
And probably that it will respond in a certain way. In fact, we all do  
this all the time; it would drive one crazy (and perhaps _be_ crazy) to  
do a “responds\_to?” before every method call. But, even in a relatively  
“innocent” case like this, the type of the object is the sum of what it  
can do at that moment, and the only measure of that is to measure it.

Of course you _could_ apply the technique you’ve used elsewhere:

if ducktype(duckHerder, spender)  
duckHerder.buy …

But my point is that, even if you don’t (and at some point one has to  
stop!), you’re still dealing with “duck typing” – even if, in a given  
case, you deal with it by deciding to trust to the percentages (the  
unlikelihood that the object’s interface has been altered) perhaps in  
combination with a suite of tests.

In any case, the main thing is the underlying thing – the dynamism and  
extensibility of Ruby objects, and the implications this has for “type”.  
I tend to think of the notion of duck typing as a way of encapsulating  
the idea: “‘type’ in Ruby is, at best, something you can only know after  
the fact, and fleetingly, so don’t put too much weight on it.”

David

> **···**
>
> On Sat, 9 Aug 2003, Mills Thomas (app1tam) wrote:
> 
> > > -----Original Message-----
> 
> –  
> David Alan Black  
> home: [dblack@superlink.net](mailto:dblack@superlink.net)  
> work: blackdav@shu.edu  
> Web: [http://pirate.shu.edu/~blackdav](http://pirate.shu.edu/~blackdav)

---

<div class="post-metadata">

**Author:** ![Dave\_Mail\_Archive](https://avatars.discourse-cdn.com/v4/letter/d/f04885/32.png) [@Dave\_Mail\_Archive](https://rubytalk.org/u/Dave_Mail_Archive)\
**Post date:** [8 August 2003 17:25 UTC](https://rubytalk.org/t/ducktype-right/7297/3 "2003-08-08T17:25:24Z")

</div>

Mills Thomas (app1tam) wrote:

> I guess I’m not sure what duck typing is, then. My example was assuming I  
> was using the original method from my first post. Thus, duckness is a list  
> of ducky methods. My second example was selling myRobot to a duckHerder  
> since, for all intents and purposes, myRobot acts like a duck. The  
> duckHerder would also consider myRobot to be a duck, assuming we agreed on  
> duckness. I thought that was duck-typing.

Duck typing is way of thinking about programming in Ruby.

For folks who come from languages such as Java or C++, types are  
basically the same as classes. When you ask ‘what is the type of  
“cat”?’, the answer comes back as ‘String’.

These languages use the type==class model as the model for programming.  
You say

```
 String fred;

```

to say that ‘fred’ has type ‘String’, and the language implements that  
by saying that fred can only reference objects that are class String.

Ruby doesn’t use that model. In Ruby, types are defined as the  
capabilities of objects. Classes can be used to give objects their  
initial capabilities, but from that point on, the class is (almost)  
irrelevant. When I write

```
 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).

I call this duck typing for two reasons. First, because the name fits  
(the “walk like a duck” business). Second, because I want to give a name  
to it to remind folks that Ruby’s type model _is_ different.

Cheers

Dave

---

<div class="post-metadata">

**Author:** ![Ben\_Giddings](https://avatars.discourse-cdn.com/v4/letter/b/b19c9b/32.png) [@Ben\_Giddings](https://rubytalk.org/u/Ben_Giddings)\
**Post date:** [8 August 2003 17:51 UTC](https://rubytalk.org/t/ducktype-right/7297/4 "2003-08-08T17:51:51Z")

</div>

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!)

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.

Ben

> **···**
>
> 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).

---

<div class="post-metadata">

**Author:** ![Ryan\_Dlugosz](https://avatars.discourse-cdn.com/v4/letter/r/c2a13f/32.png) [@Ryan\_Dlugosz](https://rubytalk.org/u/Ryan_Dlugosz)\
**Post date:** [8 August 2003 18:19 UTC](https://rubytalk.org/t/ducktype-right/7297/5 "2003-08-08T18:19:21Z")

</div>

Ben Giddings said:

> 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.

You’re correct. If you need an object to respond to, say, 3 different  
methods, then you should check to see that it responds to those three  
methods (if you aren’t confident that it will) - no more and no less than  
the three that you need.

If the object responds to the methods that you need, then there’s no  
reason for it to have to be of a specific type/implement a specific  
interface. It does what you need it to do & that’s all you should care  
about.

At least, this is how I understand the concept of Duck Typing…

-Ryan

> **···**
>
> –  
> Ryan Dlugosz  
> [ryan@dlugosz.net](mailto:ryan@dlugosz.net)
> 
> [http://dlugosz.net](http://dlugosz.net)

---

<div class="post-metadata">

**Author:** ![Chris\_Morris](https://avatars.discourse-cdn.com/v4/letter/c/6de8d8/32.png) [@Chris\_Morris](https://rubytalk.org/u/Chris_Morris)\
**Post date:** [8 August 2003 18:36 UTC](https://rubytalk.org/t/ducktype-right/7297/6 "2003-08-08T18:36:34Z")

</div>

Ben Giddings wrote:

> 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.

I agree with Ryan’s reply to you. If I only need the one method on the  
object I’m interacting with – should that one call not be allowed  
simply because all of the other methods that I don’t need aren’t  
consistent with what it _should_ be?

> **···**
>
> –
> 
> Chris  
> [http://clabs.org/blogki](http://clabs.org/blogki)

---

<div class="post-metadata">

**Author:** ![HAL\_9000](https://avatars.discourse-cdn.com/v4/letter/h/90ced4/32.png) [@HAL\_9000](https://rubytalk.org/u/HAL_9000)\
**Post date:** [8 August 2003 19:33 UTC](https://rubytalk.org/t/ducktype-right/7297/7 "2003-08-08T19:33:26Z")

</div>

> > ```
> > 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

> **···**
>
> ----- Original Message -----  
> From: “Ben Giddings” [ben@thingmagic.com](mailto:ben@thingmagic.com)  
> To: “ruby-talk ML” [ruby-talk@ruby-lang.org](mailto:ruby-talk@ruby-lang.org)  
> Sent: Friday, August 08, 2003 12:51 PM  
> Subject: Re: Ducktype, right?
> 
> > On Fri August 8 2003 1:25 pm, Dave Thomas wrote:
> 
> –  
> Hal Fulton  
> [hal9000@hypermetrics.com](mailto:hal9000@hypermetrics.com)

---

<div class="post-metadata">

**Author:** ![Ben\_Giddings](https://avatars.discourse-cdn.com/v4/letter/b/b19c9b/32.png) [@Ben\_Giddings](https://rubytalk.org/u/Ben_Giddings)\
**Post date:** [8 August 2003 19:14 UTC](https://rubytalk.org/t/ducktype-right/7297/8 "2003-08-08T19:14:36Z")

</div>

Ouch, this is one of the most difficult-to-understand sentences I’ve seen in a  
long time.

I’ll pretend I understand it and give an example:

> **···**
>
> On Fri August 8 2003 2:36 pm, Chris Morris wrote:
> 
> > Ben Giddings wrote:  
> > I agree with Ryan’s reply to you. If I only need the one method on the  
> > object I’m interacting with – should that one call not be allowed  
> > simply because all of the other methods that I don’t need aren’t  
> > consistent with what it _should_ be?
> 
> # 
> 
> # Get the contents of the object, if it acts like a string,
> 
> # simply return it, if it acts like a file, return its contents,
> 
> # if it acts like a frobnitz, foozle it.
> 
> # 
> 
> def getContents(obj)  
> if obj.respond\_to? :read  
> return obj.read  
> elsif obj.respond\_to? :to\_str  
> return obj.to\_str  
> elsif obj.respond\_to? :foozle  
> return obj.foozle  
> end  
> end
> 
> class EmailMessageBody \< String
> 
> attr\_accessor :read
> 
> def initialize  
> @read = false # By default, mark the message body as unread  
> end  
> end
> 
> Imagine that the “getContents” method is buried deeply within the source code  
> to a library somewhere. The programmer would never see that method, even if  
> he/she did see the commenting of the method. Now what happens when I pass an  
> EmailMessageBody into getContents? It will see that it responds to “read”  
> and return a boolean. That’s not what you want. That’s not what the  
> documentation says, but that’s what it will do. This could be a really hard  
> bug to track down.
> 
> Testing to see if the “read” method is supported is not really “duck typing”,  
> in the sense that you’re not really checking to see if it’s a duck. Just  
> because the object implements a certain method doesn’t mean that that method  
> does what you expect.
> 
> In certain cases, checking to see if a method exists is enough. The method  
> “to\_str” is a prime example. If someone implements that method in a way that  
> doesn’t return a string, they deserve whatever problems they get. There are  
> plenty of examples of how to\_str is used everywhere else, and the function  
> name is pretty descriptive. Other functions are less obvious.
> 
> Somebody else gave this example (though I added the “implements Duck” that I  
> think was just accidentally left out):
> 
> interface Duck  
> {  
> void quack();  
> }
> 
> class MyDuck implements Duck  
> {  
> void quack()  
> {  
> System.exit();  
> }  
> }
> 
> Here the “implements Duck” is essentially an agreement saying “I want other  
> peole to see this as a Duck”. You’re free to break that agreement, but if  
> you do, you can expect trouble.
> 
> On the other hand:
> 
> class Psychiatrist  
> {  
> void quack()  
> {  
> quack\_references++;  
> }  
> void shrink()  
> {  
> shrink\_references++;  
> }  
> }
> 
> Just because someone has a “quack” function/method, doesn’t mean they want  
> their object to be treated as a Duck. When you create a class and add  
> methods to it, should you always have to say: “Hmm, what’s the most popular  
> way \_\_\_\_\_ is used”, and make sure yours acts the same way?
> 
> My understanding was always that “implements Foo” in Java meant: “my class  
> will define the following methods, in the way that Foo describes, so you can  
> treat my class as a Foo”.
> 
> As for the subject of why it is useful to implement a set of methods rather  
> than just the one you care about, consider a function like:
> 
> def dumpContents(obj)  
> if obj.respond\_to? :write  
> obj.write(data)  
> obj.flush if obj.respond\_to? :flush  
> obj.close if obj.respond\_to? :close  
> elsif …  
> end  
> end
> 
> I think it would be much more clear if you could simply say:
> 
> def dumpContents(obj)  
> if obj.implements\_interface? :WriteableIO  
> obj.write(data)  
> obj.flush  
> obj.close  
> elsif …  
> end  
> end
> 
> Ben

---

<div class="post-metadata">

**Author:** ![Olivier\_Nenert](https://avatars.discourse-cdn.com/v4/letter/o/958977/32.png) [@Olivier\_Nenert](https://rubytalk.org/u/Olivier_Nenert)\
**Post date:** [8 August 2003 19:32 UTC](https://rubytalk.org/t/ducktype-right/7297/9 "2003-08-08T19:32:42Z")

</div>

(Hi I’m a new comer, just reading the first  
lines of ruby code and I’m already dazzled)

> Ben Giddings wrote:
> 
> > 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.
> 
> I agree with Ryan’s reply to you. If I only need the one method on the  
> object I’m interacting with – should that one call not be allowed simply  
> because all of the other methods that I don’t need aren’t consistent with  
> what it _should_ be?

I think that what Ben means isn’t to replace this actual can\_you\_do\_that?  
way of thinking, but to extend it, just as there’s nothing wrong with your  
argument:  
“if all you need from the object is to execute this method, it doesn’t  
matter what it is per se,  
as long as it does it”, the idea of implementing an interface comes  
naturaly as an extension.  
(I don’t program in java, so maybe what he talks about is actualy  
different, but that’s how I understand it myself and how I wish to create  
my own object model).  
it says “I declare that I act like a duck” that doesn’t mean “I am a duck”,  
nothing prevents me from also being able to behave like an elephant or  
whatever,  
even if in the end what i realy am is a completely different object.

while asking an obejct if he is able to execute a particular method is very  
useful,  
the interface idea is much more powerful _and_ useful.  
first, the method\_can\_do? can lead to confusion, maybe I tell you  
yes I can switch on, and yes I can switch off…  
so, as a general object manager-scheduler, when I fall in your grasp  
you say "this one I can ‘pause’ and run later.  
However, I’m part of a lightning control system, and all I do is switch  
lights on and off.

the fact is, sooner or later, you’ll have to consider that after all, even  
if my type isn’t realy important,  
the can\_you\_do\_that? idea is just as misleading, when you want me to  
execute this method,  
it’s not because of the method itself, but because you want me to “behave a  
certain way”  
(like a duck) I think it’s better to ask me if I can behave like a duck and  
then ask me to quack,  
then ask me if I can quack, and then make me do something totaly unrelated  
to the “duck quacking idea”  
(maybe I start “quack arena” :)).

But of course, those confusions could be avoided by chosing wisely the  
method names (there _will_  
however exist collisions, that’s unavoidable) and, clearly, in the very  
same way, a duck interface  
could be also confused, so the interface idea is not realy to prevent name  
collisions, but  
to show that in the end what you want is a global behavior, not just a  
particular action…

But the great advantage of a whole interface presentation would be for  
greater automated interactions  
between objects, you could for instance, declare an object as being this-  
interface-friendly and by simply  
asociating them, have them work automaticaly together. behind a well  
defined interface lie several methods  
but also several “receptors” we’d know how to use.  
I also hope ruby ducktyping goes in this direction, it would be of extreme  
usefulness, especialy in the case of distributed ruby where we should be  
able to make high level services interact intelligently with very few  
“duck-taping” code in between.

Olivier.

---

<div class="post-metadata">

**Author:** ![Lyle\_Johnson6](https://avatars.discourse-cdn.com/v4/letter/l/bb73d2/32.png) [@Lyle\_Johnson6](https://rubytalk.org/u/Lyle_Johnson6)\
**Post date:** [8 August 2003 19:50 UTC](https://rubytalk.org/t/ducktype-right/7297/10 "2003-08-08T19:50:07Z")

</div>

Ben Giddings wrote:

> Testing to see if the “read” method is supported is not really “duck typing”,  
> in the sense that you’re not really checking to see if it’s a duck. Just  
> because the object implements a certain method doesn’t mean that that method  
> does what you expect.
> 
> In certain cases, checking to see if a method exists is enough. The method  
> “to\_str” is a prime example. If someone implements that method in a way that  
> doesn’t return a string, they deserve whatever problems they get. There are  
> plenty of examples of how to\_str is used everywhere else, and the function  
> name is pretty descriptive. Other functions are less obvious.

This is a great summary of the kind of limits I place on relying on duck  
typing.

The name of a method, by itself, rarely tells you everything that you  
need to know about the method’s “contract”. Don’t get me wrong: I /like/  
the idea of using #respond\_to? instead of #is\_a? when trying to  
determine an object’s capabilities, but am very conservative with this  
approach. If I’m checking for a method name that is extremely well  
established by the standard library, and one for which no one in their  
right mind would change the semantics (e.g. #to\_str), then I’ll take  
advantage of that. Otherwise I tend to shy away from this approach.

This might be a good thing to document, either on the Wiki or in the  
next edition of Programming Ruby: what are some of the “standard” method  
names that people should be aware of?

---

<div class="post-metadata">

**Author:** ![David\_A\_Black2](https://avatars.discourse-cdn.com/v4/letter/d/57b2e6/32.png) [@David\_A\_Black2](https://rubytalk.org/u/David_A_Black2)\
**Post date:** [8 August 2003 19:50 UTC](https://rubytalk.org/t/ducktype-right/7297/11 "2003-08-08T19:50:43Z")

</div>

Hi –

> Testing to see if the “read” method is supported is not really “duck typing”,  
> in the sense that you’re not really checking to see if it’s a duck. Just  
> because the object implements a certain method doesn’t mean that that method  
> does what you expect.

No specific thing you or I do in a program is “duck typing”. As Dave  
Thomas explained, “duck typing” is a way of thinking about programming  
in Ruby. It’s more a matter of “Ruby exhibits the ‘duck typing’  
principle,” than a matter of “You can do duck typing in Ruby.”

(I know this sound perhaps ridiculous pedantic. But if this term’s  
connotations get redefined, we’ll just have to come up with another term  
to mean what Dave originally meant by “duck typing,” and that seems like  
extra work 🙂

[…]

> As for the subject of why it is useful to implement a set of methods rather  
> than just the one you care about, consider a function like:
> 
> def dumpContents(obj)  
> if obj.respond\_to? :write  
> obj.write(data)  
> obj.flush if obj.respond\_to? :flush  
> obj.close if obj.respond\_to? :close  
> elsif …  
> end  
> end
> 
> I think it would be much more clear if you could simply say:
> 
> def dumpContents(obj)  
> if obj.implements\_interface? :WriteableIO  
> obj.write(data)  
> obj.flush  
> obj.close  
> elsif …  
> end  
> end

You can certainly do something quite similar to that:

module WriteableIO

# …

end

obj.extend(WriteableIO) # or include in class, or whatever

if obj.is\_a?(WriteableIO)

# …

end

but you _still_ are playing in Ruby’s ballpark, which means that,  
theoretically, obj could also have been extended by another module  
which overrides WriteableIO’s methods, or have had one of those  
methods overridden, and so on.

This is, I think, why many Ruby programmers are also fanatical unit  
testers.

David

> **···**
>
> On Sat, 9 Aug 2003, Ben Giddings wrote:
> 
> –  
> David Alan Black  
> home: [dblack@superlink.net](mailto:dblack@superlink.net)  
> work: blackdav@shu.edu  
> Web: [http://pirate.shu.edu/~blackdav](http://pirate.shu.edu/~blackdav)

---

<div class="post-metadata">

**Author:** ![Chris\_Morris](https://avatars.discourse-cdn.com/v4/letter/c/6de8d8/32.png) [@Chris\_Morris](https://rubytalk.org/u/Chris_Morris)\
**Post date:** [8 August 2003 20:34 UTC](https://rubytalk.org/t/ducktype-right/7297/12 "2003-08-08T20:34:46Z")

</div>

Ben Giddings wrote:

> > Ben Giddings wrote:  
> > I agree with Ryan’s reply to you. If I only need the one method on the  
> > object I’m interacting with – should that one call not be allowed  
> > simply because all of the other methods that I don’t need aren’t  
> > consistent with what it _should_ be?
> 
> Ouch, this is one of the most difficult-to-understand sentences I’ve seen in a  
> long time.

Wow … you’re right. That’s ludicrous … must be Friday 🙂

Back to your first post I replied to:

> 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.

I guess I just enjoy the freedom Ruby gives me. Statements like “You  
weren’t allowed to implement the interface and then only choose certain  
features” now bug me, because a required typing system has gotten in my  
way too many times in my Delphi coding.

As David Black pointed out, Rubyists tend to be fanatical unit testers.  
Quite possibly I’m just not writing complex enough systems where your  
point would make more sense to me (honestly, not sarcastically) – I  
automate tests on the stuff I write so it seems I don’t really have to  
worry too much about contracts and the like. The places where I can just  
stick in a method name and not be bound to all these contracts and class  
hierarchy restrictions has been very pleasant.

Ironically, the few places I can think of that I am checking for this  
sort of thing, I’m doing is\_a? checks instead of responds\_to? checks 🙂

> **···**
>
> > On Fri August 8 2003 2:36 pm, Chris Morris wrote:
> 
> –
> 
> Chris  
> [http://clabs.org/blogki](http://clabs.org/blogki)

---

<div class="post-metadata">

**Author:** ![Dan\_Doel](https://avatars.discourse-cdn.com/v4/letter/d/13edae/32.png) [@Dan\_Doel](https://rubytalk.org/u/Dan_Doel)\
**Post date:** [8 August 2003 21:10 UTC](https://rubytalk.org/t/ducktype-right/7297/13 "2003-08-08T21:10:44Z")

</div>

Someone suggested that the discussion of what duck typing is is getting  
away from how it was originally used.

Perhaps I’m confused, or I’m not explaining what I think in the correct  
way, so I’ll try again.

Maybe a better way of phrasing the concepts of duck typing is contract  
typing.

If you look at Java, interfaces more-or-less define contracts between  
objects. If you have an interface Appendable, that’s a contract that  
says an object will

```
a) Have a method append()
b) Implement that in a certain way

```

a) can be had in Ruby via respond\_to?, the use of which isn’t required  
for duck typing. b) can be had more explicitly by using modules.  
However, modules, in my mind, are more for reusing code between class  
hierarchies without requiring multiple inheritance, rather than for  
defining what methods an object implements (although they could be used  
for the latter).

If you really want to talk about duck typing, you’d be talking about an  
example along the lines of:

def add\_elements(foo)  
foo \<\< "a"  
foo \<\< "b"  
end

This method accepts an array (foo) and adds two elements to it using the  
append operator. However, looked at more abstractly, this method takes  
any object for which \<\< implies append in an array sense. We could  
actually pass in a binary search tree where \<\< adds an element to the  
three, and it would work in a similar way. If we pass in a Fixnum where  
\<\< is bitwise shift, then we’ve broken the contract.

In Java, you need interfaces for this. You could write:

void addElements(Array foo)  
{  
foo.append(“a”);  
foo.append(“b”);  
}

void addElements(BST foo)  
{  
foo.append(“a”);  
foo.append(“b”);  
}

But it’s easier to have both implement Appendable, and have addElements  
work on anything that is Appendable. Java needs interfaces because of  
static type checking. In ruby you can just assume that an object  
implements things correctly and use it as such, which, I think, is the  
idea of duck typing.

If you want to make it more general, you can add a respond\_to? :\<\< and  
respond\_to? :append, since different objects might implement either or  
both of those. However, the key idea is that in ruby, the contracts are  
dynamic. Using Java interfaces, to some degree, forces you to follow  
the contracts more explicitly, since you have to knowingly say you  
implement a contract and continue to break that contract. However,  
assuming that the contract is documented somewhere in the code, and  
everybody follows that contract, then there is no need to explicitly  
define modules or classes just to define the contract in code, rather  
than leaving it in documentation. If you do define modules for each  
semantic, then you end up with each of your classes including 10  
different modules just so that code can check and see if a class follows  
some contract (look through the Java standard library and you’ll see  
many classes like this). You’re effectively turning ruby into a  
statically typed language where all the type checking is done by you at  
runtime.

So another way of saying “duck typing” is “programming with implicit  
contracts” or “implicit contract typing” or something like that, rather  
than Java, where implicit is replaced with explicit. This is really  
something of a feature of any language that isn’t statically typed. The  
difference in the case of ruby is that, although you can check the class  
of an object with is\_a? (or something like that), there’s no way to tell  
from the class itself whether it will satisfy the contract. You have to  
assume it does.

So having respond\_to? :quack doesn’t make it a duck. It’s also how quack  
is implemented, and there’s no way to really check that without  
testing. Duck typing means making assumptions.

Anyhow, that’s my take on it all, at the end of the day. I hope I’m not  
too off base. If I am, then Dave can yell at me.

- Dan

---

<div class="post-metadata">

**Author:** ![Dave\_Mail\_Archive](https://avatars.discourse-cdn.com/v4/letter/d/f04885/32.png) [@Dave\_Mail\_Archive](https://rubytalk.org/u/Dave_Mail_Archive)\
**Post date:** [8 August 2003 21:46 UTC](https://rubytalk.org/t/ducktype-right/7297/14 "2003-08-08T21:46:26Z")

</div>

Dan Doel wrote:

> So having respond\_to? :quack doesn’t make it a duck. It’s also how quack  
> is implemented, and there’s no way to really check that without  
> testing. Duck typing means making assumptions.
> 
> Anyhow, that’s my take on it all, at the end of the day. I hope I’m not  
> too off base. If I am, then Dave can yell at me.

Great summary!

In general, if a Ruby programmer finds themselves using respond\_to? too  
much, I’d ask them ‘why?’.

If they’re switching on the result, then I’d recommend looking at  
polymorphic solutions, or possibly double dispatch.

If they’re checking parameters, I’d suggest commenting out the check and  
seeing what happens. 🙂

Quack!

Dave

---

<div class="post-metadata">

**Author:** ![Jim\_Weirich2](https://avatars.discourse-cdn.com/v4/letter/j/ecc23a/32.png) [@Jim\_Weirich2](https://rubytalk.org/u/Jim_Weirich2)\
**Post date:** [8 August 2003 23:29 UTC](https://rubytalk.org/t/ducktype-right/7297/15 "2003-08-08T23:29:24Z")

</div>

I’m tacking on a big ME TOO to this post. From reading this thread, I  
get the impression that folks are talking about Duck Typing as if it  
involves using responds\_to?.

Duck typing itself has little to do with using responds\_to?. Duck  
typing is what we do every day in Ruby where we don’t explicitly declare  
types by inheriting from a classes or interfaces. We just implement the  
methods needed (with the proper semantics).

The responds\_to? thread has more to do with type discovery, which is a  
pretty interesting topic itself (although I agree with Dave where he  
says too much type discovery might be better served by polymorphism or  
double dispatch).

Just don’t confuse type discovery (e.g. using responds\_to?) with Duck  
Typing.

> **···**
>
> On Fri, 2003-08-08 at 15:50, [dblack@superlink.net](mailto:dblack@superlink.net) wrote:
> 
> > No specific thing you or I do in a program is “duck typing”. As Dave  
> > Thomas explained, “duck typing” is a way of thinking about programming  
> > in Ruby. It’s more a matter of “Ruby exhibits the ‘duck typing’  
> > principle,” than a matter of “You can do duck typing in Ruby.”
> 
> ## – – Jim Weirich [jweirich@one.net](mailto:jweirich@one.net)[http://onestepback.org](http://onestepback.org)
> 
> “Beware of bugs in the above code; I have only proved it correct,  
> not tried it.” – Donald Knuth (in a memo to Peter van Emde Boas)

---

<div class="post-metadata">

**Author:** ![Tim\_Bates](https://avatars.discourse-cdn.com/v4/letter/t/3da27b/32.png) [@Tim\_Bates](https://rubytalk.org/u/Tim_Bates)\
**Post date:** [8 August 2003 23:48 UTC](https://rubytalk.org/t/ducktype-right/7297/16 "2003-08-08T23:48:10Z")

</div>

This is something like my approach to Duck Typing. The documentation of  
my library says that this method parameter expects a Duck _or similar_.  
The actual code does no checking of whether it’s a Duck or a Giraffe, or  
even if it can quack; it just asks it to quack. If I’m feeling  
particularly zealous, I even document what methods of Duck I actually  
use. Then, it’s up to the user of my library: if they pass in a Goose,  
and it can quack, good for them. If they pass in a Mouse, they can  
expect things to break. It’s probably not the most robust of coding  
styles, but I write my libraries for intelligent people (ie me), not to  
be foolproof. Of course, I perform lots of sanity checking on my  
end-user input. 😉

Tim Bates

> **···**
>
> On Sat, Aug 09, 2003 at 06:46:26AM +0900, Dave Thomas wrote:
> 
> > In general, if a Ruby programmer finds themselves using respond\_to? too  
> > much, I’d ask them ‘why?’.
> > 
> > If they’re switching on the result, then I’d recommend looking at  
> > polymorphic solutions, or possibly double dispatch.
> > 
> > If they’re checking parameters, I’d suggest commenting out the check and  
> > seeing what happens. 🙂
> 
> –  
> tim@bates.id.au

---

<div class="post-metadata">

**Author:** ![Brian\_Candler](https://avatars.discourse-cdn.com/v4/letter/b/5f9b8f/32.png) [@Brian\_Candler](https://rubytalk.org/u/Brian_Candler)\
**Post date:** [9 August 2003 07:22 UTC](https://rubytalk.org/t/ducktype-right/7297/17 "2003-08-09T07:22:00Z")

</div>

Just as an aside, it’s respond\_to? not responds\_to?

(like Array#include? not being Array#includes?)

Cheers,

Brian.

> **···**
>
> On Sat, Aug 09, 2003 at 08:29:24AM +0900, Jim Weirich wrote:
> 
> > Duck typing itself has little to do with using responds\_to?. Duck  
> > typing is what we do every day in Ruby where we don’t explicitly declare  
> > types by inheriting from a classes or interfaces. We just implement the  
> > methods needed (with the proper semantics).
> > 
> > The responds\_to? thread has more to do with type discovery

---

<div class="post-metadata">

**Author:** ![Jim\_Weirich2](https://avatars.discourse-cdn.com/v4/letter/j/ecc23a/32.png) [@Jim\_Weirich2](https://rubytalk.org/u/Jim_Weirich2)\
**Post date:** [9 August 2003 13:22 UTC](https://rubytalk.org/t/ducktype-right/7297/18 "2003-08-09T13:22:11Z")

</div>

I guess that shows how often I use it. 🙂

> **···**
>
> On Sat, 2003-08-09 at 03:22, Brian Candler wrote:
> 
> > > The responds\_to? thread has more to do with type discovery
> > 
> > Just as an aside, it’s respond\_to? not responds\_to?
> > 
> > (like Array#include? not being Array#includes?)
> 
> ## – – Jim Weirich [jweirich@one.net](mailto:jweirich@one.net)[http://onestepback.org](http://onestepback.org)
> 
> “Beware of bugs in the above code; I have only proved it correct,  
> not tried it.” – Donald Knuth (in a memo to Peter van Emde Boas)

---

<div class="post-metadata">

**Author:** ![HAL\_9000](https://avatars.discourse-cdn.com/v4/letter/h/90ced4/32.png) [@HAL\_9000](https://rubytalk.org/u/HAL_9000)\
**Post date:** [9 August 2003 18:21 UTC](https://rubytalk.org/t/ducktype-right/7297/19 "2003-08-09T18:21:27Z")

</div>

Likewise.

BTW, for people who actually care: If you’re “thinking  
in English” in these situations (bothered by the lack  
of a “s”), you can always insert a “does” in front of  
the interrogative:

x.respond\_to? y # Does x respond to y?  
x.include? y # Does x include y?

Just my $0.01,  
Hal

> **···**
>
> ----- Original Message -----  
> From: “Jim Weirich” [jweirich@one.net](mailto:jweirich@one.net)  
> To: “ruby-talk ML” [ruby-talk@ruby-lang.org](mailto:ruby-talk@ruby-lang.org)  
> Sent: Saturday, August 09, 2003 8:22 AM  
> Subject: Re: Ducktype, right?
> 
> > On Sat, 2003-08-09 at 03:22, Brian Candler wrote:
> > 
> > > > The responds\_to? thread has more to do with type discovery
> > > 
> > > Just as an aside, it’s respond\_to? not responds\_to?
> > > 
> > > (like Array#include? not being Array#includes?)
> > 
> > I guess that shows how often I use it. 🙂
> 
> –  
> Hal Fulton  
> [hal9000@hypermetrics.com](mailto:hal9000@hypermetrics.com)

---

<div class="post-metadata">

**Author:** ![Brian\_Candler](https://avatars.discourse-cdn.com/v4/letter/b/5f9b8f/32.png) [@Brian\_Candler](https://rubytalk.org/u/Brian_Candler)\
**Post date:** [9 August 2003 19:11 UTC](https://rubytalk.org/t/ducktype-right/7297/20 "2003-08-09T19:11:24Z")

</div>

Nice thought, although it still doesn’t read very well with “if” or  
“unless”:

if does x.respond\_to? y  
…  
end

Maybe “if x does respond\_to? y”, or “if x can/will respond\_to? y”

Cheers,

Brian.

> **···**
>
> On Sun, Aug 10, 2003 at 03:21:27AM +0900, Hal E. Fulton wrote:
> 
> > BTW, for people who actually care: If you’re “thinking  
> > in English” in these situations (bothered by the lack  
> > of a “s”), you can always insert a “does” in front of  
> > the interrogative:
> > 
> > x.respond\_to? y # Does x respond to y?  
> > x.include? y # Does x include y?
> > 
> > Just my $0.01,
