Ruby的多態性是指不同對象可以對同一消息作出不同的響應。這意味著你可以使用一個接口來表示不同類型的對象,從而提高代碼的復用性。多態可以通過以下幾種方式提高代碼復用性:
class Animal
def speak
puts "I am an animal."
end
end
class Dog < Animal
def speak
puts "Woof!"
end
end
class Cat < Animal
def speak
puts "Meow!"
end
end
animal = Animal.new
dog = Dog.new
cat = Cat.new
animal.speak # 輸出 "I am an animal."
dog.speak # 輸出 "Woof!"
cat.speak # 輸出 "Meow!"
module Greeting
def greet
puts "Hello, my name is #{name}."
end
end
class Person
include Greeting
def initialize(name)
@name = name
end
end
class Employee < Person
include Greeting
def initialize(name, title)
super(name)
@title = title
end
end
person = Person.new("Alice")
person.greet # 輸出 "Hello, my name is Alice."
employee = Employee.new("Bob", "Software Engineer")
employee.greet # 輸出 "Hello, my name is Bob."
def process_item(item)
if item.is_a?(String)
puts "Processing string: #{item}"
elsif item.is_a?(Integer)
puts "Processing integer: #{item}"
else
puts "Unknown item type: #{item.class}"
end
end
process_item("Hello") # 輸出 "Processing string: Hello"
process_item(42) # 輸出 "Processing integer: 42"
process_item(3.14) # 輸出 "Unknown item type: Float"
通過使用繼承、模塊和方法參數,Ruby的多態性可以幫助你編寫更加靈活、可擴展和可復用的代碼。