From: Peter Booth Date: 2006-09-14T06:57:12+09:00 Subject: Re: How to collect over two arrays then look back to one? Thank you for taking the time to do this. I learnt at least five things new things about Ruby from your email. -----Original Message----- From: Gavin Kistner [mailto:gavin.kistner@anark.com] Sent: Wednesday, September 13, 2006 12:27 PM To: ruby-talk@ruby-lang.org Subject: Re: How to collect over two arrays then look back to one? From: Peter Booth [mailto:pbooth@marketaxess.com] > 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] ---------------------------------------------------------------------------- ---------------------------------------- The information contained in and accompanying this communication is strictly confidential and intended solely for the use of the intended recipient(s). If you have received it by mistake please let us know by reply and then delete it from your system; you should not copy the message or disclose its content to anyone. MarketAxess reserves the right to monitor the content of emails sent to or from its systems. Any comments or statements made are not necessarily those of MarketAxess. For more information, please visit www.marketaxess.com. MarketAxess Europe Limited is regulated in the UK by the FSA, registered in England no. 4017610, registered office at 71 Fenchurch Street, London, EC3M 4BS. Telephone (020) 7709 3100. MarketAxess Corporation is regulated in the USA by the SEC and the NASD, incorporated in Delaware, executive offices at 140 Broadway, New York, NY 10005. Telephone (1) 212 813 6000.