是的,Ruby的多态性可以与其他特性结合使用,以实现更强大和灵活的编程。以下是一些与多态性结合使用的Ruby特性:
class Animal
def speak
puts "The animal makes a sound"
end
end
class Dog < Animal
def speak
puts "The dog barks"
end
end
class Cat < Animal
def speak
puts "The cat meows"
end
end
animals = [Dog.new, Cat.new]
animals.each(&:speak)
class Calculator
def multiply(a, b)
puts "Multiplication: #{a * b}"
end
def multiply(a, b, c)
puts "Triple multiplication: #{a * b * c}"
end
end
calc = Calculator.new
calc.multiply(2, 3) # 输出 "Multiplication: 6"
calc.multiply(2, 3, 4) # 输出 "Triple multiplication: 24"
module Logger
def log(message)
puts "Logging: #{message}"
end
end
class MyClass
include Logger
def do_something
log("Doing something")
end
end
my_obj = MyClass.new
my_obj.do_something # 输出 "Logging: Doing something"
class Shape
def area
raise NotImplementedError, "This method should be overridden by subclasses"
end
end
class Circle < Shape
def initialize(radius)
@radius = radius
end
def area
Math::PI * @radius * @radius
end
end
class Rectangle < Shape
def initialize(width, height)
@width = width
@height = height
end
def area
@width * @height
end
end
shapes = [Circle.new(5), Rectangle.new(4, 6)]
shapes.each(&:area)
总之,Ruby的多态性可以与其他特性结合使用,以实现更强大、灵活和可维护的代码。