let's say that I have two-dimensional arrays
array= [[10,12,15,17],[16,32,65,47],[45,48,41,23],[36,25,74,98], [32,19,66,88],...]
I would like to do this in ruby
arr = [[10+45+32+..,12+48+19,15+41+66+..,17+23+88+..], [16+36+..,32+25+..,65+74+..,47+98+..]
Thank you in advance.
Use
partition
to separate and collect the even-indexed sub-arrays and odd-indexed sub-arrays. Then transpose each partition, followed by the sum of each newly formed sub-array.key methods:
Enumerable#partition
,Integer#even?
andArray#transpose
. See ruby-docs for more info. If you're using Ruby versions < 2.4.0, useinject(:+)
instead ofsum
, as follows: