# Ruby Duck Typing, Dynamic Dispatch, and Singleton Classes

DevFeed: [Ruby Duck Typing, Dynamic Dispatch, and Singleton Classes](<https://devfeed.tech/articles/i-object-21038.md>)

Original publisher: [Read original article](<https://jakeyesbeck.com/2015/08/23/ruby-objects/>)

Published: 2015-08-23T12:00:00Z

Content type: tutorial

Language: en

Sources: [Jake Yesbeck](<https://devfeed.tech/sources/jake-yesbeck.md>)

Topics: [Ruby](<https://devfeed.tech/topics/ruby.md>), [coding](<https://devfeed.tech/topics/coding.md>)

Tags: [class](<https://devfeed.tech/tags/class.md>), [coding](<https://devfeed.tech/tags/coding.md>), [object](<https://devfeed.tech/tags/object.md>), [ruby](<https://devfeed.tech/tags/ruby.md>), [superclass](<https://devfeed.tech/tags/superclass.md>)

## AI overview

This tutorial explains Ruby's duck typing and dynamic dispatch, then shows how singleton classes store methods specific to individual objects and affect method lookup.

## Source excerpt

I am lucky enough to work with wonderfully talented people every single day. This is a guest post by one of my magnificent coworkers, Kristján Pétursson. Thank you for allowing me to share this knowledge with everyone! This post is adapted from my answer to this Stack Overflow question. If you want to start from the beginning of the universe and build out, go read that one. If you prefer to start with something you can touch and work backwards, here we go. Ruby likes ducks. Which is to say that when we're coding, and we have an object, we don't particularly care what kind of object it is, so long as it responds to the messages we send it. It might be a Duck or a Child or a Doctor, and as long as when we call #quack we hear a noise, all is well. That's called Duck Typing, and Ruby digs it. So if we have some arbitrary object and we ask it to #quack, the Ruby interpreter needs to figure out where the object's #quack method is. Nothing's been compiled, and Ruby lets you define methods pretty much any place or time you like, so #quack needs to be looked up at runtime. That's called Dynamic dispatch, and it's how Ruby handles ducks. Now for the thing we can touch; let's make a Duck class Duck def quack puts "Quack, I say!" end end duck = Duck.new duck.quack #=> Quack, I say! Surely, this is no surprise. You've done this in the past, or quieter things like it, and you understand just fine that a method called on duck will be found in Duck. But we less frequently do things like: def duck.quack puts "I'm tired of quacking." end duck.quack #=> I'm tired of quacking. other_duck = Duck.new other_duck.quack #=> Quack, I say! Hm, so if we can just redefine duck.quack without messing up other_duck, where is the second #quack method? It turns out every object has a Singleton Class where it can stash all its personal possessions. Other words for singleton class include metaclass, eigenclass, and virtual class, but Ruby implements a method called #singleton_class, so we'll use that