Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Multiply all elements of an array

Tags:

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?

like image 622
Mexxer Avatar asked Aug 13 '11 14:08

Mexxer


People also ask

How do you multiply in Ruby?

The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/).

What is inject in Ruby?

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.

Can you print an array in Ruby?

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.

How do you use reduce in Ruby?

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.


1 Answers

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(:*) 
like image 52
DGM Avatar answered Oct 13 '22 19:10

DGM