[Ruby] How to change a string in an array to a number in Ruby

1 minute read

array = ["1", "2", "3", "4", "5"]

When there is a numeric value of a character string in the array like this, write the method to change the character string of the array to a numerical value.

for statement method

array = ["1", "2", "3", "4", "5"]

intArray = []
for n in array
  intArray.push(n.to_i)
end

# intArray => [1, 2, 3, 4, 5]

Create an array intArray = [] which is different from the array array. Repeat the process of acquiring the value of array with n, changing the character string to a numeric value with to_i, and assigning the value to intArray with push.

Method of #map method

array = ["1", "2", "3", "4", "5"]

intArray = array.map{ |n| n.to_i}

# intArray => [1, 2, 3, 4, 5]

Or

array = ["1", "2", "3", "4", "5"]

intArray = array.map(&:to_i)

# intArray => [1, 2, 3, 4, 5]

The array array is repeatedly processed by the map method, the value is assigned to the variable n, and the processing n.to_i or &:to_i is executed as the desired processing. Substitute the executed process into intArray. In this case, it is not necessary to define it in advance like intArray = [].

There is also a way to use map!, in this case

array = ["1", "2", "3", "4", "5"]

array.map!{ |n| n.to_i}

# array => [1, 2, 3, 4, 5]

You can rewrite the array of array like.

Reference site

https://techacademy.jp/magazine/19868 https://uxmilk.jp/21695

Tags:

Updated: