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

From: Peter B. [mailto:[email protected]]

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]