【问题标题】:Referencing a local variable from a Proc defined in another scope从另一个作用域中定义的 Proc 引用局部变量
【发布时间】:2011-05-03 13:27:36
【问题描述】:

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

例如,假设以下类是扩展的,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 的调用者中引用局部变量?

【问题讨论】:

    标签: ruby proc-object


    【解决方案1】:

    我不希望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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-14
      • 1970-01-01
      • 2021-07-06
      • 2017-07-21
      • 1970-01-01
      • 2016-10-07
      • 2017-12-22
      相关资源
      最近更新 更多