Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply the elements of an array using array#each?

Tags:

arrays

ruby

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
like image 475
user1404456 Avatar asked Dec 06 '22 12:12

user1404456


1 Answers

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(:*)
like image 186
David Robles Avatar answered Jan 06 '23 09:01

David Robles