Duck Typing (Ruby)

Duck typing is Ruby's approach to types: what matters is whether an object responds to the methods you call, not its class. 'If it walks like a duck and quacks like a duck, it's a duck.'

Ruby

Ruby doesn't check an object's declared type before calling a method; it just sends the message and sees if the object responds. So any object with a quack method can be used wherever 'something that quacks' is expected, regardless of its class or ancestry.

This makes code flexible and decoupled: a method works with any object implementing the needed interface, which is great for testing (pass a stub that responds the same way) and for polymorphism without inheritance. You can check capability explicitly with obj.respond_to?(:method).

The trade-off is that type mismatches surface at runtime (a NoMethodError) rather than at compile time. Duck typing pairs naturally with 'everything is an object' and is why Ruby favors behavior-based design over rigid class hierarchies.

Examples

Ruby

def make_it_speak(animal)
  animal.speak
end

class Dog; def speak; "woof"; end; end
class Cat; def speak; "meow"; end; end

puts make_it_speak(Dog.new)
puts make_it_speak(Cat.new)

Output:

woof
meow

Learn it in a lesson

See also

Back to the Dictionary