在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中定義具有高代碼復用性的類。