简而言之:我想在继承到所有子类的超类中定义算法,但我想将子类中的数据(算法在其上运行)定义为实例变量,当我调用“新”给定类的方法。在 Ruby 中执行此操作的标准方法是什么?
我的解决方案是(但我不确定这是正确的方法):
class A
attr_accessor :var
def initialize
@var=nil #I dont know the actual value, it will be defined only in the more specific subclasses.
end
def process_data
puts @var #simply puts it out
end
end
#in my program all further classes are inherited form class A, the processing facility is inherited, only the data varies.
class B < A
attr_accessor :var
def initialize
@var=10 #specific value for class B which is always 10, no need for example b=B.new(20)
end
end
class C < A
attr_accessor :var
def initialize
@var=20 #specific value for class C which is always 20, no need for example c=C.new(20)
end
end
b=B.new
b.process_data #needs to print 10
c=C.new
c.process_data #needs to print 20