문제

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?

도움이 되었습니까?

해결책

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 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top