是的,Ruby的多態(tài)性可以與其他特性結(jié)合使用,以實(shí)現(xiàn)更強(qiáng)大和靈活的編程。以下是一些與多態(tài)性結(jié)合使用的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的多態(tài)性可以與其他特性結(jié)合使用,以實(shí)現(xiàn)更強(qiáng)大、靈活和可維護(hù)的代碼。