I have a stumbling block due to a ruby problem, so I will keep it as a record.
The following is a rough explanation of the problem. ・ Two numbers are entered as a character string ("a b") ・ I want to give a number that doubles each final
Wrong answer
num = gets.split.map(&:to_i)
puts num * 2
Split the value with the split
method and put the string value in the array.
Create an array by converting the values of the array to numbers with `map (&: to_i)`
. (Regarding ``` map (&: to_i)` ``, the following article is very easy to understand and I used it as a reference.)
https://a-records.info/ruby-map-ampersand-colon-to_i/
Perform * 2 on the elements of the array.
The result is as follows.
num = gets.split.map(&:to_i) //Enter 5 10
puts num * 2
Output result=> 5 10 5 10
I didn't understand why 5 10 was repeated twice even though I was converting to a number with @ map (&: to_i)
.
-Multiplication of an array creates a new array that repeats the same elements. The elements were repeated because we were doing * 2 on the array itself, not on each element. (I think that's the case if you review it after understanding it ...)
num = gets.split.map(&:to_i)
num.each {|n| puts n * 2}
It was solved by processing each element with `ʻeach``.
Recommended Posts