我尝试在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
类中创建某个特定子类的实例?
提前致谢。
答案 0 :(得分:5)
是
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