Reputation: 95
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?
Upvotes: 0
Views: 99
Reputation: 37409
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
Upvotes: 3