0
下面的代碼字符串數組轉換成float數組:如何將字符串數組的數組轉換爲Ruby中的浮點數?
a = ["4", "5.5", "6"]
a.collect do |value|
value.to_f
end
=> [4.0, 5.5, 6.0]
爲什麼下面的返回一個字符串,而不是float數組?
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"]]
另外,有沒有更好的方法來做到這一點?
這工作.... – 2012-03-13 03:28:28
'arr.map(:to_f)'是有點短 – 2012-03-13 16:03:57