From: Dave Burt Date: 2006-03-29T14:03:42+09:00 Subject: Re: How to interator over two arrays? "brez! !!" asked: > Let me start by saying I really like Ruby iterators - anyhow I've been > taking every opportunity to use the single line syntax like: > > StopWord.find(:all).each{ |x| @stop_words << x.stopword } > > yea! > ... > #assumes equal size arrays! > def dotproduct(doc, query) > @product = Array.new(doc.length) > @i = 0 > doc.each do |term| > @product[@i] = term * query[@i] > @i += 1 > end > return sum(@product) > end > > Any thoughts on getting this into single-line syntax? Just curious. Here ya go: dotproduct = doc.zip(query).inject(0) {|sum, (d, q)| sum + d * q } Cheers, Dave