Duck Typing in Ruby?

In Ruby, type is determined by behavior (methods), not class.
If an object can perform required actions, it can be used.

def make_it_talk(obj)
  obj.talk
end

class Dog
  def talk; puts "Woof!"; end
end

class Human
  def talk; puts "Hello!"; end
end

make_it_talk(Dog.new)   # Woof!
make_it_talk(Human.new) # Hello!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *