Ruby方法对多维数组中的所有值求和 [英] Ruby method to sum all values in a multidimensional array

查看:158
本文介绍了Ruby方法对多维数组中的所有值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对数组的元素求和.不使用展平.我尝试使用以下内容:

I am trying to sum the elements of an array. WITHOUT using flatten. I have tried using the following:

def multi_array_sum(arr)
  sum = 0
  arr.each do |row|
    row.each do |column|
      sum += column
    end
  end
  return sum
end

但不幸的是,它无法正常工作.考虑到如果数组中的第一个元素不是另一个数组本身(例如array = [[1, [1, 2], [3, 4, 5]]),则不能使用each,因此我不确定如何遍历多维数组.

but unfortunately, it is not working. I am not sure how to iterate though a multidimensional array considering that I cannot use each if the first element in the array is not another array itself, for example, array = [[1, [1, 2], [3, 4, 5]].

推荐答案

如果所有元素都是数字或数组,并且您想对它们全部求和:

If all elements are numeric or arrays, and you want to sum them all:

array.flatten.inject(:+)

这篇关于Ruby方法对多维数组中的所有值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆