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.