Mexxer Mexxer - 1 month ago 8
Ruby Question

Rails 3: Multiply all elements of an array

Let's say I have an array A = [1, 2, 3, 4, 5]

how can I multiply all elements with ruby and get the result? 1*2*3*4*5 = 120

and what if there is an element 0 ? How can I ignore this element?

DGM DGM
Answer

This is the textbook case for inject (also called reduce)

[1, 2, 3, 4, 5].inject(:*)

As suggested below, to avoid a zero,

[1, 2, 3, 4, 5].reject(&:zero?).inject(:*)