红宝石:两个数组的总和对应的成员 [英] ruby: sum corresponding members of two arrays

查看:122
本文介绍了红宝石:两个数组的总和对应的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个(或更多)阵列,在每个12个整数(值相对应的每个月)。我想要的是将它们添加在一起,这样我得为每月汇总值单个阵列。这里有三个值的示例:
[1,2,3]和[4,5,6] => [5,7,9]

I've got two (or more) arrays with 12 integers in each (corresponding to values for each month). All I want is to add them together so that I've got a single array with summed values for each month. Here's an example with three values: [1,2,3] and [4,5,6] => [5,7,9]

我能想出的最好成绩是:

The best I could come up with was:

[[1,2,3],[4,5,6]].transpose.map{|arr| arr.inject{|sum, element| sum+element}} #=> [5,7,9]

是否有这样做的更好的办法?这似乎只是这样一个基本的事情要做。

Is there a better way of doing this? It just seems such a basic thing to want to do.

推荐答案

这里的版本阿努拉格建议:

Here's the transpose version Anurag suggested:

a.transpose.map {|x| x.reduce(:+)}

这将与任意数量的分量数组的工作。 减少是同义词,但减少在我看来,在这里更清楚地传达code的意图...

This will work with any number of component arrays. reduce and inject are synonyms, but reduce seems to me to more clearly communicate the code's intent here...

这篇关于红宝石:两个数组的总和对应的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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