B Seven
B Seven

Reputation: 45941

How to convert an array of arrays from string to float in Ruby?

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?

Upvotes: 2

Views: 5373

Answers (1)

Ben Taitelbaum
Ben Taitelbaum

Reputation: 7403

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.map{ |arr| arr.map{ |v| v.to_f } }

Upvotes: 12

Related Questions