在Ruby中,动态派发是指在运行时根据接收者对象的类型来确定调用哪个方法。这种灵活性使得可以根据不同的情况来执行不同的操作,而不需要在编码时确定调用的方法。
动态派发可以应用在很多场景中,比如根据用户输入的不同命令来执行不同的操作,根据不同的数据类型来调用不同的处理方法等。以下是一个简单的示例:
class Animal def make_sound raise NotImplementedError, "Subclasses must implement make_sound method" endendclass Dog < Animal def make_sound puts "Woof!" endendclass Cat < Animal def make_sound puts "Meow!" endenddef make_animal_sound(animal) animal.make_soundenddog = Dog.newcat = Cat.newmake_animal_sound(dog) # 输出 Woof!make_animal_sound(cat) # 输出 Meow!在这个示例中,make_animal_sound方法根据传入的动物对象来调用make_sound方法,而不需要在编写方法时指定调用哪个子类的方法。这样就实现了动态派发的功能。


