8

Sometimes when I try to print a Float in rails, I get an error like this:

TypeError at /delivery_requests/33/edit
no implicit conversion of Float into String

on the line: 
= this_is_a_float

I know I can just add .to_s to the float, but why is this not done by default?

1
  • Why should it be done by default? Commented Jan 14, 2014 at 5:57

2 Answers 2

15

This is because you're using a Float in place where a String is expected like the following example:

"Value = " + 1.2 # => no implicit conversion of Float into String

To fix this you must explicitly convert the Float into a String

"Value = " + 1.2.to_s # => Value = 1.2
Sign up to request clarification or add additional context in comments.

2 Comments

So, is the reason that this is not done by default (like in Java where System.out.print can handle almost all datatypes) is because in Ruby, 1.2 could be interpreted as a function on 1? But even then, couldn't Ruby try to do 1.2.to_s?
I don't know exactly why Ruby doesn't do it the same as Java.
4

This post is old, so a little bit of an update for future readers. Rather than doing to_s which works, you can simply do string interpolation. It's also faster and more memory efficient.

x = 0.005
"With string interpolation: #{x}"  # => "With string interpolation: 0.005"
"Standard to_s method: " + x.to_s  # => "Standard to_s method: 0.005"

You can also do directly (tho, admittedly silly):

"string interpolation: #{0.005}"  # => "string interpolation: 0.005"

String interpolation is the way to go in Rails apps, mostly if you're pulling in ActiveRecord objects' various datatypes. It'll automatically .to_s it for you properly, and you simply need to call it as model.value instead of model.value.to_s.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.