# Re: How to collect over two arrays then look back to one?

**URL:** <https://www.ruby-forum.com/t/re-how-to-collect-over-two-arrays-then-look-back-to-one/68574>\
**Category:** Ruby\
**Created:** [September 13, 2006, 6:27pm UTC](https://www.ruby-forum.com/t/re-how-to-collect-over-two-arrays-then-look-back-to-one/68574 "2006-09-13T18:27:49Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![phrogz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/2acd7d/32.png) [@phrogz](https://www.ruby-forum.com/u/phrogz)\
**Post date:** [September 13, 2006, 6:27pm UTC](https://www.ruby-forum.com/t/re-how-to-collect-over-two-arrays-then-look-back-to-one/68574/1 "2006-09-13T18:27:49Z")

</div>

From: Peter B. [[mailto:removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)]

> Two parallel arrays A, B . For each element n of A for which  
> f(An) is true,  
> is g(B[n-3:n+3]) true? Where B[n-3:n+3] refers to seven  
> elements of B whose  
> position is centered over An’ position.
> 
> Can the block inside Enumerable#collect know it’s position inside the  
> Enumerable? Can one collect two parallel arrays?

#collect\_with\_index doesn’t exist natively (but should)

#zip will merge the arrays, and then you can map the results.

module Enumerable  
def map\_with\_index  
a = []  
each\_with\_index { |x, i|  
a \<\< yield( x, i )  
}  
a  
end  
end

class Array  
def sum  
inject(0){ |s,v| s+v }  
end  
end

def f( n )  
n % 2 == 0  
end

def g( \*vals )  
vals.sum  
end

a = (1…10).to\_a  
b = (10…20).to\_a

pairs = a.zip( b )  
odd\_sums = pairs.map\_with\_index{ |pair, i|  
a\_val = pair[0]  
if f( a\_val )  
b\_vals = pairs[(i-3)…(i+3)].map{ |pair| pair[1] }  
g( \*b\_vals )  
else  
nil  
end  
}

p odd\_sums  
#=\> [nil, 0, nil, 91, nil, 105, nil, 99, nil, 70]
