用ruby中的数字连接字符串

its*_*ode 66 ruby

我是红宝石的初学者,所以这是一个非常新手的问题.

我试图连接一个字符串与浮动值,如下所示,然后打印它.

puts " Total Revenue of East Cost: " + total_revenue_of_east_cost 
Run Code Online (Sandbox Code Playgroud)

total_revenue_of_east_cost是一个保持浮点值的变量,我怎样才能打印?

Ste*_*yle 99

这不是完全连接,但它将完成您想要做的工作:

puts " Total Revenue of East Cost: #{total_revenue_of_east_cost}"
Run Code Online (Sandbox Code Playgroud)

从技术上讲,这是插值.区别在于连接添加到字符串的末尾,其中插值计算一些代码并将其插入到字符串中.在这种情况下,插入位于字符串的末尾.

Ruby将在字符串中的大括号之间评估任何东西,其中开头括号前面有一个octothorpe.

  • octothorpe是美国代言哈希;) (6认同)

Ste*_*eet 52

Stephen Doyle的答案,使用一种称为"字符串插值"的技术是正确的,可能是最简单的解决方案,但还有另一种方法.通过调用对象to_s方法,该对象可以转换为字符串进行打印.所以以下内容也适用.

puts " Total Revenue of East Cost: " + total_revenue_of_east_cost.to_s
Run Code Online (Sandbox Code Playgroud)

  • BTW:如果插值表达式的结果不是"String",字符串插值会自动调用`to_s`. (2认同)

ede*_*ill 7

对于您的示例,您可能需要比to_s方法更具体的内容.毕竟,浮点数上的to_s通常包含比您希望显示的精度更高或更低的精度.

在这种情况下,

puts " Total Revenue of East Coast: #{sprintf('%.02f', total_revenue_of_east_coast)}"
Run Code Online (Sandbox Code Playgroud)

可能会更好.#{}可以处理任何ruby代码,因此您可以使用sprintf或任何其他您想要的格式化方法.


Ste*_*elm 5

我喜欢(详见Class String%):

puts " Total Revenue of East Coast: " + "%.2f" % total_revenue_of_east_coast
Run Code Online (Sandbox Code Playgroud)