user3686152
user3686152

Reputation: 23

Return an array of multiple 2 using created method

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

Answers (1)

raina77ow
raina77ow

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 * intnew_ary

ary * strnew_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 ]

Upvotes: 1

Related Questions