Ruby: Multiply all elements of an array

前端 未结 4 1561
孤城傲影
孤城傲影 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:50

    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(:*)
    

提交回复
热议问题