Sunday, January 20, 2008

If you are going to use inject to sum up an attribute of an object (such as amount), make sure you give an initial value. Don't do this:

@total_savings = @coupons.inject { |sum, coupon| sum + coupon.amount }

because you will get an error:

undefined method `+' for #<Coupon:0x4398ee8>

It is trying to pass in the first coupon object as the initial sum parameter to your block. Instead, do this:

@total_savings = @coupons.inject(0) { |sum, coupon| sum + coupon.amount }

Then, it passes 0 as the first value of sum.

Obvious? Once you see it, it sure is, but this confused me for a bit. I hope it helps someone else in the future (probably me).

Sunday, January 20, 2008 10:40:47 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]