Ruby的多態性允許對象對不同的對象做出響應,就像它們是對相同的方法的調用一樣。這種特性可以極大地提高代碼的靈活性和可擴展性。為了優化Ruby代碼結構,可以通過以下方式利用多態性:
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?
方法:這個方法可以用來檢查一個對象是否對某個特定的方法有定義,從而決定是否調用它。def animal_sound(animal)
if animal.respond_to?(:speak)
animal.speak
else
"This animal doesn't speak."
end
end
send
方法:這個方法允許你調用對象上的任何方法,只要你知道方法名。def animal_sound(animal, method_name)
animal.send(method_name)
end
通過這些方法,你可以利用Ruby的多態性來編寫更加靈活、可維護和可擴展的代碼。