从另一个作用域中定义的 Proc 引用局部变量

发布于 2024-11-04 19:10:53 字数 694 浏览 0 评论 0原文

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

例如,假定扩展以下类,并且 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ぽ尐不点ル 2024-11-11 19:10:53

我不希望在 pricing_rule 返回的 Proc 内部访问 discount_price 的局部变量。传入 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

I wouldn't expect discount_price's local variables to be accessible inside the Proc returned by pricing_rule. Passing prices in will work:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文