我尝试在Ruby中定义操作语义,仅用于学习目的.我想定义一些操作:add,multiply,subtraction,division.
这是代码:
class Operation < Struct.new(:left, :right) def inspect "#{self}" end def reducible? true end end class Add < Operation def to_s "#{left} + #{right}" end def reduce if left.reducible? Add.new(left.reduce, right) elsif right.reducible? Add.new(left, right.reduce) else Number.new(left.value + right.value) end end end class Multiply < Operation def to_s "#{left} * #{right}" end def reduce if left.reducible? Multiply.new(left.reduce, right) elsif right.reducible? Multiply.new(left, right.reduce) else Number.new(left.value + right.value) end end end
是否有可能有相同的东西,但reduce
在Operation
类中定义,但在类中创建一些特定子类的实例Operation
?
提前致谢.
是.
class Operation def reduce if left.reducible? self.class.new(left.reduce, right) elsif right.reducible? self.class.new(left, right.reduce) else Number.new(left.value + right.value) end end end