Link to a local variable from Proc defined in another scope

I want to create an instance method that changes its behavior with the return value of another method depending on the implementation of it being rewritable in a polymorphic way.

For example, it is assumed that the next class will be extended and pricing_ruleshould vary from product to 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 run the local error of the undefined variable at startup. Although I understand that the Proc instance refers to the Purchase instance, I sometimes encountered similar situations, I need to place the variable pricesin the discount_price method. Is there a smarter way to reference a local variable in a Proc caller?

+3
source share
1 answer

, discount_price Proc, pricing_rule. 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
+4

All Articles