DEV Community

loading...
Cover image for 49 Days of Ruby: Day 22 - Duck Typing

49 Days of Ruby: Day 22 - Duck Typing

Ben Greenberg
Rabbi turned Coder. Second Career Dev taking it one function at a time.
・2 min read

Welcome to day 22 of the 49 Days of Ruby! 🎉

If you have been reading about Ruby, you might have come across a term called duck typing. Today we are going to spend some time discussing this idea and how it pertains to your code.

What is Duck Typing?

If it walks like a duck, then it is a duck.

Have you heard that expression before? If so, that's pretty much duck typing!

Ruby is less concerned about the type of a thing, and more about what it does. (We are going to cover types tomorrow!)

Take a look at the following example:

class Duck
  def walk
    puts "I'm walking"
  end
end

class Turkey
  def walk
    puts "I'm walking"
  end
end
Enter fullscreen mode Exit fullscreen mode

Did you notice that both Duck and Turkey have a #walk method? Does that make a Turkey a Duck? Well, if we're following duck typing, then it really doesn't matter. As long as an Object responds to a method then that's all that really matters.

How do we check if it knows that method (or message, is another way of stating it)?

We can try the #respond_to? Ruby method, which does what it sounds like. It checks if an Object recognizes the message you are sending it. Continuing our example of a Duck and a Turkey:

> Duck.respond_to?(:walk)

# => true

> Turkey.respond_to?(:walk)

# => true
Enter fullscreen mode Exit fullscreen mode

They both know #walk so for all intents and purposes you can treat both the Duck and the Turkey as a Duck!

That's it for today! See you tomorrow as we discuss typing in Ruby.

Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.

Discussion (0)