从另一个作用域中定义的 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 的实例是指 Purchasing 的实例,但有时我会遇到类似的情况,我需要将 prices
变量放入discount_price 方法中。有没有更聪明的方法来引用 Proc 的调用者中的局部变量?
I want to create an instance method which varies its behaviour with return value of another method depending on a implementation of its overwrites in a polymorphic manner.
For example, the following class is assumed to be extended and pricing_rule
is supposed to change depending on a product.
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>
But, I'm getting an undefined local variable error when I run this. Though I understand that the instance of Proc refers to an instance of Purchase, I sometimes encountered similar situations I need to place prices
variable into discount_price method. Is there any smarter way to refer to local variable in a caller of a Proc?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不希望在
pricing_rule
返回的Proc
内部访问discount_price
的局部变量。传入prices
即可:I wouldn't expect
discount_price
's local variables to be accessible inside theProc
returned bypricing_rule
. Passingprices
in will work: