Ruby的多態(tài)性允許對(duì)象對(duì)不同的對(duì)象做出響應(yīng),就像它們是對(duì)相同的方法的調(diào)用一樣。這種特性可以極大地提高代碼的靈活性和可擴(kuò)展性。為了優(yōu)化Ruby代碼結(jié)構(gòu),可以通過(guò)以下方式利用多態(tài)性:
class Animal
def speak
raise NotImplementedError, "Subclass must implement this method"
end
end
class Dog < Animal
def speak
"Woof!"
end
end
class Cat < Animal
def speak
"Meow!"
end
end
animals = [Dog.new, Cat.new]
animals.each(&:speak) # 輸出: ["Woof!", "Meow!"]
def make_sound(animal)
animal.speak
end
module Swimmable
def swim
"I can swim!"
end
end
class Duck < Animal
include Swimmable
end
duck = Duck.new
puts duck.swim # 輸出: "I can swim!"
respond_to?
方法:這個(gè)方法可以用來(lái)檢查一個(gè)對(duì)象是否對(duì)某個(gè)特定的方法有定義,從而決定是否調(diào)用它。def animal_sound(animal)
if animal.respond_to?(:speak)
animal.speak
else
"This animal doesn't speak."
end
end
send
方法:這個(gè)方法允許你調(diào)用對(duì)象上的任何方法,只要你知道方法名。def animal_sound(animal, method_name)
animal.send(method_name)
end
通過(guò)這些方法,你可以利用Ruby的多態(tài)性來(lái)編寫更加靈活、可維護(hù)和可擴(kuò)展的代碼。