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

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

arr = ["5", "-7", "1", "-2"]
new_arr = arr.map { | item | item.to_i }

print new_arr #=> [5, -7, 1, -2]

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

arr = ["5", "-7", "1", "-2"]
new_arr = arr.map(&:to_i)

print new_arr #=> [5, -7, 1, -2]

Using either of the above would create a new array with all numeric strings in the array converted to integer. 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", "-2"]
arr.map!(&:to_i)

print arr #=> [5, -7, 1, -2]

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.