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
def make_sound(animal)
animal.speak
end
dog = Dog.new
cat = Cat.new
puts make_sound(dog) # 輸出 "Woof!"
puts make_sound(cat) # 輸出 "Meow!"
respond_to?
方法:在方法內部使用 respond_to?
方法檢查對象是否實現了所需的方法,然后根據結果調用相應的方法。def make_sound(animal)
if animal.respond_to?(:speak)
animal.speak
else
"This animal doesn't make a sound."
end
end
module Swimmable
def swim
"I can swim!"
end
end
class Duck < Animal
include Swimmable
end
class Fish < Animal
include Swimmable
end
duck = Duck.new
fish = Fish.new
puts duck.swim # 輸出 "I can swim!"
puts fish.swim # 輸出 "I can swim!"
any?
和 all?
方法:在集合中使用多態性,可以輕松地檢查集合中的所有對象是否實現了所需的方法。animals = [Dog.new, Cat.new, Duck.new]
can_speak = animals.all?(&:speak)
puts can_speak # 輸出 true
通過遵循這些建議,你可以利用 Ruby 的多態性來編寫更靈活、可維護和可擴展的代碼。