在Ruby中将Float转换为String

时间:2014-01-14 05:41:55

标签: ruby-on-rails ruby

有时当我尝试在rails中打印Float时,我会收到如下错误:

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

on the line: 
= this_is_a_float

我知道我可以将.to_s添加到浮点数,但为什么默认情况下不会这样做?

2 个答案:

答案 0 :(得分:13)

这是因为您正在使用Float,其中需要String,如下例所示:

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

要解决此问题,您必须将Float显式转换为字符串

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

答案 1 :(得分:2)

这篇文章很老,所以对未来的读者来说是一点点更新。您可以简单地进行字符串插值,而不是使to_s工作。它也更快,内存效率更高。

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"

你也可以直接做(因此,诚然愚蠢):

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

字符串插值是Rails应用程序的一种方式,主要是因为你要提取ActiveRecord对象的各种数据类型。它会自动.to_s为您正确,您只需将其称为model.value而不是model.value.to_s