What is Duck Typing in Ruby: Simple Explanation and Example
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.
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
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.