When I tried to convert the numbers in the array, I stumbled and checked how to write I will make a note for myself as a memorandum.
When trying to convert the number of strings in an array I got an error.
array.rb
Traceback (most recent call last):
array.rb:3:in `<main>': undefined method `to_i' for ["1", "2", "3", "4", "5"]:Array (NoMethodError)
Did you mean? to_s
to_a
to_h
This is a summary of how to write. ↓ ↓ ↓
array.rb
num = [ "1", "2", "3", "4", "5" ]
i = 0
while i <= 4
num[i] = num[i].to_i
i += 1
end
p num
#=>[1, 2, 3, 4, 5]
array.rb
num = [ "1", "2", "3", "4", "5" ]
int = []
for i in num
int.push(i.to_i)
end
p int
#=>[1, 2, 3, 4, 5]
array.rb
num = [ "1", "2", "3", "4", "5" ]
int = num.map{ |i| i.to_i }
p int
#=>[1, 2, 3, 4, 5]
array.rb
num = [ "1", "2", "3", "4", "5" ]
int = num.map(&:to_i)
p int
#=>[1, 2, 3, 4, 5]
I couldn't convert it very well, so I took this opportunity to investigate. This seems to be a little easier to understand.
Recommended Posts