Skip to main content
4 of 5
added 5 characters in body; edited tags; edited title
Jamal
  • 34.9k
  • 13
  • 133
  • 237

Calculating shopping cart discounts

I have a method that checks to see if a hash of given items should have discounts applied and if so, determines and returns the discount:

def get_discounts
  @items.each do |name, attr|
    @specials.each do |special|
      while name == special.sale_item && attr[:quantity] >= special.quantity
        @discounts << special.discount
        attr[:quantity] = attr[:quantity] - special.quantity
      end  
    end  
  end
  determine_discount
end

def determine_discount
  if @discounts.empty?
    @discounts = 0
  else
    @discounts = @discounts.inject(:+) 
  end   
end

This works perfectly, but is there a more concise way to write it? I'm looking especially at the two each loops. I'm also a bit iffy about the while loop - it was an if statement (if name == special.sale_item) but it felt like too much so I combined it into the while loop.

dax
  • 197
  • 1
  • 7