我想创建一个实例方法,它根据以多态方式覆盖的实现来改变其行为与另一个方法的返回值。
例如,假设以下类是扩展的,并且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 的调用者中引用局部变量?