3

我想创建一个实例方法,它根据以多态方式覆盖的实现来改变其行为与另一个方法的返回值。

例如,假设以下类是扩展的,并且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

1 回答 1

4

我不希望在返回的discount_price内部可以访问 的局部变量。传入将起作用:Procpricing_ruleprices

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
于 2011-05-03T13:42:10.543 回答