Rails 3: Multiply All Array Elements

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?

+7
source share
4 answers

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

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

As shown below, to avoid zero,

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

There is another way to calculate this factorial! If you want, you can determine what your last number is, like n.

In this case, n = 5 .

From there it will look something like this:

 (1..num).inject(:*) 

This will give you 120 . In addition, .reduce() works the same.

+1
source

Well, this is a dummy way, but it works :)

 A = [1, 2, 3, 4, 5] result = 1 A.each do |i| if i!= 0 result = result*i else result end end puts result 
0
source

If you want to understand your code later, use this: Suppose A = 5, I used n instead of A

 n = 5 n.times {|x| unless x == 0; n = n * x; ++x; end} pn 

To move it forward, you must:

 A = [1,2,3,4,5] arb = A.first a = A.count a.times {|x| arb = arb * A[x]; ++x} p arb 
0
source

All Articles