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"]]
また、これを行うより良い方法がありますか?
働いたこと.... –
'arr.map(&:to_f)は'少し短いです –