Tsallaka zuwa abun ciki
Justice Tech School

Duck Typing and Polymorphism

Ruby cares what an object can do, not what class it is. If it responds to the message, it works. respond_to? tests for a method.

Example
class Dog; def speak = "Woof"; end
class Robot; def speak = "Beep"; end
[Dog.new, Robot.new, 5].each do |x|
  puts x.respond_to?(:speak) ? x.speak : "#{x} cannot speak"
end

Result

Woof
Beep
5 cannot speak

Exercise

Test for a method.

x.(:speak)

Quiz Test

What is duck typing?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.