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?
The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/).
Inject applies the block result + element. to each item in the array. For the next item ("element"), the value returned from the block is "result". The way you've called it (with a parameter), "result" starts with the value of that parameter. So the effect is adding the elements up.
Ruby printing array contentsThe array as a parameter to the puts or print method is the simplest way to print the contents of the array. Each element is printed on a separate line. Using the inspect method, the output is more readable. The line prints the string representation of the array to the terminal.
reduce(0) sets the initial value. After that, we have two parameters in the method (|sum, num|). The first parameter, which we call 'sum' here is the total that will eventually be returned. The second parameter, which we call 'num' is the current number as we iterate through the array.
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(:*)
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