2011-05-03 43 views
3

我想要創建一個實例方法,該方法根據以多態方式覆蓋的實現方式改變其行爲與另一個方法的返回值。引用另一個作用域中定義的Proc中的局部變量

例如,假定以下類被擴展,並且pricing_rule應該根據產品而改變。

class Purchase 
    def discount_price 
    prices = [100, 200, 300] 
    pricing_rule.call 
    end 
    protected 
    def pricing_rule 
     Proc.new do 
     rate = prices.size > 2 ? 0.8 : 1 
     total = prices.inject(0){|sum, v| sum += v} 
     total * rate 
     end 
    end 
end 
Purchase.new.discount_price 
#=> undefined local variable or method `prices' for #<Purchase:0xb6fea8c4> 

但是,我得到一個未定義的局部變量錯誤,當我運行這個。雖然我明白Proc的實例引用了Purchase實例,但我有時遇到類似的情況,我需要將prices變量放入discount_price方法中。在Proc的調用者中有沒有更聰明的方法來引用局部變量?

回答

4

我不希望discount_price的局部變量可以在pricing_rule返回的Proc內訪問。通過prices將工作:

class Purchase 
    def discount_price 
    prices = [100, 200, 300] 
    pricing_rule.call prices 
    end 
    protected 
    def pricing_rule 
     Proc.new do |prices| 
     rate = prices.size > 2 ? 0.8 : 1 
     total = prices.inject(0){|sum, v| sum += v} 
     total * rate 
     end 
    end 
end 
相關問題