Ruby:将String转换为Float

时间:2015-04-12 22:14:24

标签: ruby

我需要添加3个字符串变量。 a =“5.21”,b =“5.22”,c =“5.23”。 当我尝试添加我得到一个字符串时,我需要数值

我试过以下

a = a.to_f => 5.2
b = b.to_f => 5.2
c = c.to_f => 5.2
sum = a + b + c => 15.6

如何获得输出15.66。请帮忙

1 个答案:

答案 0 :(得分:4)

尝试利用Ruby内置的Enumerable方法。试试这个:

a = "5.21"
b = "5.22"
c = "5.23"

[a, b, c].map(&:to_f).inject(:+)
#=> 15.66