Ruby 是否支持“包含多态性”?这和 Duck Typing 一样吗?
如果不是,那么 Ruby 中的多态性和鸭子类型有什么区别?
有人可以用我下面的例子来说明:
# superclass - inheritance
class Animal
def make_noise
# define abstarct method (force override)
raise NoMethodError, "default make_noise method called"
end
end
# module - composition
module Fur
def keep_warm
# etc
end
end
# subclass = is-a relationship
class Bird < Animal
# override method - polymorphism
def make_noise
"Kaaw"
end
end
class Cat < Animal
# module mixin = has-a relationship
include Fur
def make_noise
"Meow"
end
end
class Radio
# duck typing (no inheritance involved)
def make_noise
"This is the news"
end
end
class Coat
include Fur
end
animals = [Bird,Cat,Radio,Coat,Animal]
animals.each do |a|
# polymorphism or duck typing?
obj = a.new
if obj.respond_to? 'make_noise'
puts obj.make_noise
end
end