在Ruby中,多態(tài)性是指不同對象可以對同一方法作出不同的響應(yīng)。這意味著你可以使用相同的接口來處理不同類型的對象,而不需要知道它們的具體類型。要實現(xiàn)多態(tài)性,你需要使用以下方法:
class Animal
def speak
puts "The animal makes a sound"
end
end
class Dog < Animal
def speak
puts "The dog barks"
end
end
class Cat < Animal
def speak
puts "The cat meows"
end
end
animal = Animal.new
dog = Dog.new
cat = Cat.new
animal.speak # 輸出 "The animal makes a sound"
dog.speak # 輸出 "The dog barks"
cat.speak # 輸出 "The cat meows"
module Greeting
def greet
puts "Hello, I am a friendly object"
end
end
class Person
include Greeting
end
class Animal
include Greeting
end
person = Person.new
animal = Animal.new
person.greet # 輸出 "Hello, I am a friendly object"
animal.greet # 輸出 "Hello, I am a friendly object"
respond_to?
方法:這個方法允許你檢查對象是否實現(xiàn)了特定的方法,從而在運行時確定應(yīng)該調(diào)用哪個實現(xiàn)。class Animal
def speak
puts "The animal makes a sound"
end
end
class Dog < Animal
def speak
puts "The dog barks"
end
end
class Cat < Animal
def speak
puts "The cat meows"
end
end
def make_sound(animal)
if animal.respond_to?(:speak)
animal.speak
else
puts "This animal doesn't make a sound"
end
end
animal = Animal.new
dog = Dog.new
cat = Cat.new
make_sound(animal) # 輸出 "The animal makes a sound"
make_sound(dog) # 輸出 "The dog barks"
make_sound(cat) # 輸出 "The cat meows"
通過使用這些方法,你可以在Ruby中處理不同類型的對象,而無需關(guān)心它們的具體類型。這就是Ruby多態(tài)性的基本概念。