如何在Ruby中将数组数组从string转换为float?

时间:2022-01-13 21:43:43

The following code converts an array of strings to an array of floats:

以下代码将字符串数组转换为浮点数组:

a = ["4", "5.5", "6"]
a.collect do |value| 
  value.to_f 
end
=> [4.0, 5.5, 6.0]

Why does the following return an array of strings instead of floats?

为什么以下返回一个字符串数组而不是浮点数?

b =  [ ["0.0034", "-0.0244", "0.0213", "-0.099"], 
       ["0.0947", "-0.1231", "-0.1363", "0.0501"], 
       ["-0.0368", "-0.1769", "-0.0327", "-0.113"], 
       ["0.0936", "-0.0987", "-0.0971", "0.1156"], 
       ["0.0029", "-0.1109", "-0.1226", "-0.0133"] ]

b.each do |row| 
    row.collect do |value|
        value.to_f
    end
end
=> [["0.0034", "-0.0244", "0.0213", "-0.099"], ["0.0947", "-0.1231", "-0.1363", "0.0501"], ["-0.0368", "-0.1769", "-0.0327", "-0.113"], ["0.0936", "-0.0987", "-0.0971", "0.1156"], ["0.0029", "-0.1109", "-0.1226", "-0.0133"]]

Also, is there a better way to do this?

另外,有更好的方法吗?

1 个解决方案

#1


11  

Because you're calling each on b instead of collect, you end up returning the original array instead of a newly created array. Here's the correct code (I prefer map to collect, but that's just me):

因为您在b而不是collect上调用每个,所以最终返回原始数组而不是新创建的数组。这是正确的代码(我更喜欢收集地图,但那只是我):

b.map{ |arr| arr.map{ |v| v.to_f } }

#1


11  

Because you're calling each on b instead of collect, you end up returning the original array instead of a newly created array. Here's the correct code (I prefer map to collect, but that's just me):

因为您在b而不是collect上调用每个,所以最终返回原始数组而不是新创建的数组。这是正确的代码(我更喜欢收集地图,但那只是我):

b.map{ |arr| arr.map{ |v| v.to_f } }