0

So I have to implement two different situations. One is a method that multiplies two numbers, and can also multiply more than 2 numbers.

I'm using the following:

def multiply(arr)
    arr.reduce(1, :*)
end

So far it works out fine if I unit test using an array input. Is there anyway to do this so my method can take in just two values, or an array, and return the relevant results? Is there also a way to implement this without even using an array input?

1
  • Consider using splat operator: def multiply(*arr); ...; end Commented May 8, 2014 at 12:49

1 Answer 1

3

Use the splat operator:

def multiply(*arr)
  arr.reduce(1, :*)
end

multiply(2, 3, 4, 5)
# => 120 

If you want to also want to support input as an array, you can use flatten on arr:

def multiply(*arr)
  arr.flatten.reduce(1, :*)
end

multiply([2, 3, 4, 5])
# => 120 
multiply(10, 3, 5)
# => 150 
multiply(10, 3)
# => 30 
Sign up to request clarification or add additional context in comments.

Comments

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.