Ruby: Multiply all elements of an array

前端 未结 4 1535
孤城傲影
孤城傲影 2021-02-19 05:20

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 ?

4条回答
  •  迷失自我
    2021-02-19 05:45

    There is also another way to calculate this factorial! Should you want to, you can define whatever your last number is as n.

    In this case, n=5.

    From there, it would go something like this:

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

    This will give you 120. Also, .reduce() works the same way.

提交回复
热议问题