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]

Hope you found this post useful. It was published . Please show your love and support by sharing this post.