quantity = 3Will fail 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.
amount_to_charge = price_field * quantity
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:
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!