Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have the following code for my coupon system. It should work but I'm sure I can optimize it.

Any suggestions would be welcome.

@price_to_pay = @booking_request.guests * @table_offer.price_cents / 100
@remaining = @coupon.current_amount - @price_to_pay
if @remaining > 0
  @coupon.current_amount = @remaining
  @price_to_pay = 0
elsif @remaining = 0
  @coupon.current_amount = 0
  @price_to_pay = 0
elsif @remaining < 0
  @coupon.current_amount = @remaining
  @price_to_pay = @remaining * -1

Thank you

share|improve this question
is this Rails? a lot of instance variables being used here, and some even updated (@price_to_pay), why is that? are they AR attributes? – tokland Nov 22 '12 at 15:58
up vote 2 down vote accepted

I think this replicates the logic:

price = @booking_request.guests * @table_offer.price_cents / 100
@remaining = @coupon.current_amount - price
@coupon.current_amount = @remaining
@price_to_play = @remaining >= 0 ? 0 : -@remaining

Note that I avoid setting @price_to_play to a value and changing it afterwards, that kind of variable re-using makes code harder to understand.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.