Forum: Ruby on Rails Nil being coerced to float

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
12d36b8a51ef9106b20d9a4ed65aa18f?d=identicon&s=25 Tom Harvey (babastus)
on 2009-04-01 16:16
I was doing this:

     @line_items = LineItems.find_all_by_invoice_id(params[:id])
     @payments = Payments.find_all_by_invoice_id(params[:id])

    @total = @line_items.sum{ |item| item.cost }
    @payment_total = @payments.sum{ |payment| payment.value }

    @balance = @total - @payment_total


But when no payments had been made it was coming up with an error when
trying to sum nil, so I did this:

     begin
          @payment_total = @payments.sum{ |payment| payment.value }
     rescue
          @payment_total = 0
     end

So, when the sum failed it returned @payment_total as zero. Now, SURELY,
there's a better way to do this? I'm sure it's obvious when you know
how. Please, enlighten me.
53be54e5db4dc58e4980db5a8255621b?d=identicon&s=25 Harold (Guest)
on 2009-04-01 17:42
(Received via mailing list)
All you need to do to your original code is add a condition to make
sure @payments is not null:
@payment_total = @payments.sum{ |payment| payment.value } unless
@payments.nil?

Or can payment.value be nil for some payments but not others? Inject
could help in that case:
@payment_totals = @payments.inject(0) { |sum, p| sum + p.value unless
p.value.nil? }

Before running either one of these, you can initialize both @total and
@payment_total to zero:
@total, @payment_total = 0, 0

Hope that helps.

PS: Wonder if you need all of these to be @instance_variables ?

On Apr 1, 10:16 am, Tom Harvey <rails-mailing-l...@andreas-s.net>
Aad37b5f7116c8d1f547d23b37566032?d=identicon&s=25 Greg Donald (destiney)
on 2009-04-01 23:37
(Received via mailing list)
On Wed, Apr 1, 2009 at 9:16 AM, Tom Harvey
<rails-mailing-list@andreas-s.net> wrote:
>
> I was doing this:
>
>     @line_items = LineItems.find_all_by_invoice_id(params[:id])
>     @payments = Payments.find_all_by_invoice_id(params[:id])
>
>    @total = @line_items.sum{ |item| item.cost }
>    @payment_total = @payments.sum{ |payment| payment.value }

You can do

@payment_total = @payments.sum{ |payment| payment.value } if @payments

or

@payment_total = @payments.sum{ |payment| payment.value } rescue 0

or

@payment_total = @payments ? @payments.sum{ |payment| payment.value } :
0


>     end
>
> So, when the sum failed it returned @payment_total as zero. Now, SURELY,
> there's a better way to do this? I'm sure it's obvious when you know
> how. Please, enlighten me.



--
Greg Donald
http://destiney.com/
12d36b8a51ef9106b20d9a4ed65aa18f?d=identicon&s=25 Tom Harvey (babastus)
on 2009-04-02 14:43
Thanks Guys, that's much more Ruby like code!
This topic is locked and can not be replied to.