在Ruby中,类是一种用于定义对象的蓝图。要提高代码复用性,可以通过以下方法来定义类:
class Animal
def initialize(name)
@name = name
end
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
module Loggable
def log(message)
puts "Logging: #{message}"
end
end
class MyClass
include Loggable
def initialize(name)
@name = name
end
end
module MyMixin
def my_method
puts "This is a method from the mixin"
end
end
class MyClass
include MyMixin
def initialize(name)
@name = name
end
end
class AbstractClass
def self.abstract_method
raise NotImplementedError, "This method must be overridden in a subclass"
end
end
class ConcreteClass < AbstractClass
def self.abstract_method
puts "ConcreteClass has implemented the abstract method"
end
end
通过使用这些方法,可以在Ruby中定义具有高代码复用性的类。