Ruby 的多態(tài)性允許對象對不同的消息做出響應(yīng),而不需要知道它們的具體類型。這可以提高代碼的可維護性和可擴展性。以下是一些使用多態(tài)性優(yōu)化 Ruby 代碼結(jié)構(gòu)的建議:
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?
方法:在方法內(nèi)部使用 respond_to?
方法檢查對象是否實現(xiàn)了所需的方法,然后根據(jù)結(jié)果調(diào)用相應(yīng)的方法。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?
方法:在集合中使用多態(tài)性,可以輕松地檢查集合中的所有對象是否實現(xiàn)了所需的方法。animals = [Dog.new, Cat.new, Duck.new]
can_speak = animals.all?(&:speak)
puts can_speak # 輸出 true
通過遵循這些建議,你可以利用 Ruby 的多態(tài)性來編寫更靈活、可維護和可擴展的代碼。