0
0
RubyConceptBeginner · 3 min read

What is Duck Typing in Ruby: Simple Explanation and Example

In Ruby, duck typing means an object's suitability is determined by the methods it has, not its class. If an object behaves like a duck (has the right methods), Ruby treats it as a duck, regardless of its actual type.
⚙️

How It Works

Duck typing in Ruby is like judging a tool by what it can do, not by its label. Imagine you see a bird that walks and quacks like a duck. You don't need to check its species to know it's a duck. Similarly, Ruby checks if an object can perform the methods you want to call, rather than checking its class.

This means you don't have to worry about strict types. If an object responds to the methods your code needs, Ruby will let you use it. This makes Ruby flexible and lets you write simpler, more adaptable code.

💻

Example

This example shows two different objects that both respond to the quack method. Ruby treats them the same because they behave like ducks.

ruby
class Duck
  def quack
    "Quack!"
  end
end

class Person
  def quack
    "I'm pretending to be a duck!"
  end
end

def make_it_quack(duck_like)
  puts duck_like.quack
end

duck = Duck.new
person = Person.new

make_it_quack(duck)    # Works because Duck has quack
make_it_quack(person)  # Works because Person has quack too
Output
Quack! I'm pretending to be a duck!
🎯

When to Use

Use duck typing when you want your code to be flexible and work with any object that behaves a certain way, not just objects of a specific class. This is helpful in situations like:

  • Writing methods that accept different types of objects as long as they have the needed methods.
  • Designing libraries or APIs that work with user-defined classes.
  • Reducing strict dependencies on class hierarchies, making code easier to extend.

Duck typing encourages focusing on what an object can do, which fits well with Ruby’s dynamic and expressive style.

Key Points

  • Duck typing checks if an object has the required methods, not its class.
  • It makes Ruby code flexible and easy to extend.
  • Objects just need to behave correctly to be used interchangeably.
  • It fits Ruby’s dynamic nature and reduces strict type checks.

Key Takeaways

Duck typing means focusing on what an object can do, not what it is.
Ruby allows any object with the right methods to be used interchangeably.
This approach makes code more flexible and easier to extend.
Use duck typing to accept diverse objects that share behavior.
It fits Ruby’s dynamic and expressive programming style perfectly.