Ruby:将数组的所有元素相乘 [英] Ruby: Multiply all elements of an array
本文介绍了Ruby:将数组的所有元素相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个数组 A = [1, 2, 3, 4, 5]
Let's say I have an array A = [1, 2, 3, 4, 5]
如何将所有元素与 ruby 相乘并得到结果?1*2*3*4*5 = 120
how can I multiply all elements with ruby and get the result? 1*2*3*4*5 = 120
如果有一个元素 0 呢?我怎样才能忽略这个元素?
and what if there is an element 0 ? How can I ignore this element?
推荐答案
这是注入(也称为reduce
)
[1, 2, 3, 4, 5].inject(:*)
如下所述,为了避免零,
As suggested below, to avoid a zero,
[1, 2, 3, 4, 5].reject(&:zero?).inject(:*)
这篇关于Ruby:将数组的所有元素相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文