About array multiplication

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
  1. Split the value with the split method and put the string value in the array.

  2. 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/

  3. 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).

Conclusion

-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

About array multiplication
About Java Array List
Array
Multiplication in a Ruby array
About =
Array
Explanation about Array object of Ruby
[Java] array
About Kotlin
About attr_accessor
[Ruby] Array
Java array
About Hinemos
Array practice
Java array
About params
java (array)
About Rails 6
About form_for
Java array
[Java] Array
About Spring ③
About enum
About polymorphism
About Optional
About hashes
About JitPack
About Dockerfile
Array practice 2
About this ()
About devise
About encapsulation
Java array
About Docker
About JAVA_HOME
About active_hash
About static
About exceptions
[Java beginner] About initialization of multidimensional array
12 of Array
About scope
java array
[Java] Array
[Maven] About Maven