Rietta
Rietta: Web Apps Where Security Matters
You are reading The Rietta Blog, a publication about the web since 2005.

Rails: TypeError: Nil Can't Be Coerced Into Float

When working on Ruby on Rails website some of the common errors that you need to check for is nil objects when something else was expected. For instance, suppose one of your ActiveRecord models has a price field. Further suppose that the user left this field blank instead of entering 0.0 as the price.

This computation will fail:

1
2
3
 quantity = 3
 # ...
 amount_to_charge = price_field * quantity

It fails with a “TypeError: nil can’t be coerced into Float” exception. Your user will be shown the dreaded red “We’re sorry, but something went wrong” page.

A few observations:

  • This is correct behavior because Ruby as a language cannot assume that a nil object is equivalent to 0. It will not automatically convert the value to 0 for the purposes of completing the computation.
  • nil implements to_f, which returns 0.0 as a float.
  • nil implements to_i, which returns 0 as an integer.

In the current example, it is reasonable to treat nil as a 0.0. The following will do that:

1
2
3
 quantity = 3
 # ... 
 amount_to_charge = price_field.to_f * quantity

The same will work with integers using to_i. Instances when nil can reasonably considered 0 is only something that you, as the programmer can decide. In most cases it would be better to include good validations and default values in all of your models to avoid this situation altogether.

I hope this helps!

Invitation to the Web Application Topics Newsletter

This post is part of the Web Application Topics series. If you are interested in having future issues sent directly to you by e-mail, please sign up for free, today. For back issues, see the Web Application Topics category on this blog.

About Frank Rietta

Frank Rietta's photo

Frank Rietta is specialized in working with startups, new Internet businesses, and in developing with the Ruby on Rails platform to build scalable businesses. He is a computer scientist with a Masters in Information Security from the College of Computing at the Georgia Institute of Technology. He teaches about security topics and is a contributor to the security chapter of the 7th edition of the "Fundamentals of Database Systems" textbook published by Addison-Wesley.