7.4.1. Duck typing

Attributy: section id="duck-typing" xreflabel="Duck typing"

What Duck typing is based mostly on realising what sort of operations you want to do with the object and testing for those operations, rather than testing for the class. As Dave is fond of saying: „type and class aren't the same“.

Duck typing is based mostly on realising what sort of operations you want to do with the object and just doing them, rather than worrying if the object inherits from the proper base class or interface.

I've heard others also explain duck typing in terms of explicitly testing for particular methods and I feel that leaves the wrong impression. If we say Ruby supports duck typing, then newcomers are left with the impression that you need to do a lot of testing for particular methods (which you don't).

Ukázka Duck Typing

class Dog
    def talk
        puts "Woof"
    end
end
class Duck
    def talk
        puts "Quack"
    end
end
[Dog.new, Duck.new].each { |a| a.talk }
Licence Creative Commons
Tento dokument Ruby, jehož autorem je Radek Hnilica, podléhá licenci Creative Commons Uveďte autora-Nevyužívejte dílo komerčně-Zachovejte licenci 3.0 Česká republika .