ruby:将两个或多个数组的对应成员求和 [英] ruby: sum corresponding members of two or more arrays

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

问题描述

我有两个(或更多)数组,每个数组中有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.

推荐答案

以下是Anurag建议的transpose版本:

Here's the transpose version Anurag suggested:

[[1,2,3], [4,5,6]].transpose.map {|x| x.reduce(:+)}

这将与任何数量的组件阵列一起使用. reduceinject是同义词,但是在我看来reduce可以在此处更清楚地传达代码的意图...

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...

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

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