How to Convert an Array of Numeric Strings to Floats in Ruby?

In Ruby, you can convert an array of numeric strings to an array of floats by calling the String#to_f method on each element using Array#map, for example, like so:

arr = ["5", "-7", "1.25", "-2.25"]
new_arr = arr.map { | item | item.to_f }

print new_arr #=> [5.0, -7.0, 1.25, -2.25]

You can also shorten this by using the &: syntax, for example, like so:

arr = ["5", "-7", "1.25", "-2.25"]
new_arr = arr.map(&:to_f)

print new_arr #=> [5.0, -7.0, 1.25, -2.25]

Using either of the above will create a new array with all numeric strings in the array converted to float. If you want to mutate the original array instead, then you simply need to use Array#map! instead of Array#map. For example:

arr = ["5", "-7", "1.25", "-2.25"]
arr.map!(&:to_f)

print arr #=> [5.0, -7.0, 1.25, -2.25]

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.