From: Robert Dober Date: 2006-09-14T02:11:52+09:00 Subject: Re: How to collect over two arrays then look back to one? ------=_Part_48030_33259814.1158167474558 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: quoted-printable Content-Disposition: inline On 9/13/06, Peter Booth wrote: > > I am reading Ruby for Rails and Ruby Cookbock and delighted by the > Array#find_all and Enumerable#collect methods. I'm wondering what the > idiomatic way to do the following is? > > 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? > > Peter Hmm this seems interestingly complicated - or I am just dully stupid;) Well here is what I came up with: a =3D [*1..20] b =3D a.map{ |e| "Line #{e}" } def ranges a, b, n, &block ### The following is what you were asking for ;) b.values_at(*(0..a.length-1).zip(a).map{|e| block.call(e.last) ? e.first: nil}. compact.map{|i| [*(i-n)..(i+n)]}.flatten.uniq.reject{|i|i<0}).compact end p ranges(a,b,1) { |e| (e%3).zero? } p ranges(a,b,2) { |e| (e%3).zero? } p ranges(a,b,1) { |e| (e%5).zero? } p ranges(a,b,2) { |e| (e%5).zero? } HTH Robert PS: Golfers cut it down ;) R --=20 Deux choses sont infinies : l'univers et la b=EAtise humaine ; en ce qui concerne l'univers, je n'en ai pas acquis la certitude absolue. - Albert Einstein ------=_Part_48030_33259814.1158167474558--