1

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
  • Your argument to maps method is [[1,2,3]], an array with a single element which is an array. Ruby has a peculiar property that you can multiply an array and integer and get an array with all elements duplicated. Commented Aug 14, 2022 at 11:30

1 Answer 1

1

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 ]

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your explanation. So what I did was multiplied the original array by 2, that's why I get [[1, 2, 3, 1, 2, 3]].
Yes. Technically it was called a repetition, not multiplication though. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.