Convert Float to String in Ruby

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

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

on the line: 
= this_is_a_float

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

+3
source share
2 answers

This is because you are using Float where String is expected, as in the following example:

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

To fix this, you must explicitly convert Float to string

"Value = " + 1.2.to_s # => Value = 1.2
+11
source

This post is old, so it’s a little updated for future readers. Instead of executing to_s, which works, you can simply interpolate the strings. It is also faster and more 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 stupid):

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

- Rails, , ActiveRecord. .to_s , model.value model.value.to_s.

0

All Articles