array = ["1", "2", "3", "4", "5"]
I will write a method to change the character string of the array to a number when there is a numerical value in the character string in the array like.
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 = [] that is different from ʻarray
.
The process of getting the value of ʻarray with
n, changing the character string to a numerical value with
to_i, and assigning the value to ʻintArray
with push
is repeated.
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 map
method iteratively processes the array ʻarray, assigns the value to the variable
n, and executes the process
n.to_i or
&: to_i as the process you want to execute. Substitute the executed process into ʻintArray
.
In this case, it is not necessary to define in advance like ʻintArray = [] `.
You can also 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 this.
https://techacademy.jp/magazine/19868 https://uxmilk.jp/21695
Recommended Posts