I am trying to write a method which takes as its input an array of integers and returns their product. For example:
product([1,2,3]) # returns 6
I need to do this using Array#each
and not the inject method. This is what I have come up with, but it seems to be incorrect:
def product(array)
final = 0.0
array.each do |i|
final *= i
end
return final
end
Also, how could I modify this method to return the product of all the odd integers in the array, such that
product([1,2,3]) # returns 3, because 2 is even
product([0,-1,-10]) # returns -1, because 0 and -10 are even
As Ramon said, just initialize final to 1.0:
def product(array)
final = 1.0
array.each { |i| final *= i }
final
end
However, in idiomatic Ruby:
[1, 2, 3].inject(:*)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With