Return an array of multiple 2 using created method

Viewed 33

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.

1 Answers

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 the int copies of self.

[ 1, 2, 3 ] * 3 #=> [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ]

Related