2016-01-10 136 views
1

我嘗試在Ruby中定義操作語義,僅用於學習目的。我想定義一些操作,例如:加法,乘法,減法,除法。是否可以從父類創建子類的實例?

這裏是代碼:

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 

是否有可能有同樣的事情,但在Operation類中定義reduce,但在Operation類中創建一些特別的子類的實例?

在此先感謝。

回答

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 
+1

謝謝你分享這個絕妙的主意:) – SuperManEver

相關問題