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"
endResult
Woof Beep 5 cannot speak
Exercise
Test for a method.
x.(:speak)
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.