Reputation: 23
I'm a new learner of Ruby. I'm doing an exercise which a method will take the integers in an array, multiply by 2, then return them in a new array.
Here is my code:
array = [1,2,3]
def maps(x)
x.map { |int| int*2 }
end
p maps([array])
I get the result:
[[1, 2, 3, 1, 2, 3]]
Why is that? And how should I rewrite the code so that it will return [2,4,6]? Thanks in advance.
Upvotes: 1
Views: 228
Reputation: 106375
Should be just...
p maps(array)
The way it's implemented, you actually pass an array of arrays into maps
:
p maps([[1,2,3]])
Therefore mapping function - { |int| int*2 }
- is actually invoked just once, and its argument is [1,2,3]
array. What you see is result of *
operator applied to Array * Int combination:
ary * int → new_ary
ary * str → new_string
Repetition. With a String argument, equivalent to
ary.join(str)
. Otherwise, returns a new array built by concatenating theint
copies of self.[ 1, 2, 3 ] * 3 #=> [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ]
Upvotes: 1