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的多态性可以帮助你编写更加灵活、可扩展和可复用的代码。