Ross Bamford wrote:
> Notice OP wanted to sum or multiply each element *resulting in a new
> array of summed elements*. Other solutions posted injected an array:
>
> 	arr.zip(brr).inject([]) { |ary,(a,b)| ary << a + b }

Ah yes, but if you look at the original post, you'll see that what he's
actually calculating is the dot product (a single value) and that his
code returns a single value (assuming he defined the sum method):

brez!  !! wrote:
> #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

So despite what he said, it appears what he actually wants is inject.
If so, the first response is correct:

Dave Burt wrote:
> dotproduct = doc.zip(query).inject(0) {|sum, (d, q)| sum + d * q }

The zip solution you posted isn't quite right, because it creates an
array of the sums of the elements rathar than the products and doesn't
produce the actual dot product value. I think what you meant was:

 	arr.zip(brr).inject([]) { |ary,(a,b)| ary << a * b }

But that just generates the array of products, not their sum. If both
the value and the array of products are required, I don't think there's
a one-line solution without getting really ugly. It seems to me the
original poster is confused about ruby variables. The original code
seems to use instance variables where local variables are probably more
appropriate. If this is what he really meant, then it's equivalent with
the original answer. More explicitly:

>> 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
=> nil
>> def dotproduct2(doc, query)
>>     doc.zip(query).inject(0) {|sum, (d, q)| sum + d * q }
>> end
=> nil
>> a = [1,2,3]
=> [1, 2, 3]
>> b = [4,5,6]
=> [4, 5, 6]
>> dotproduct(a, b)
NoMethodError: undefined method `sum' for main:Object
        from (irb):8:in `dotproduct'
        from (irb):15
        from :0
>> def sum(e)
>>     e.inject {|i,j| i+j}
>> end
=> nil
>> dotproduct(a, b)
=> 32
>> dotproduct2(a, b)
=> 32

> And I was just generally commenting that any time you inject an array
> and want a one-for-one transformation you can avoid that and use map. I
> obviously didn't mean that #map is a general-purpose alternative to
> #inject...

Oh, sorry. I was just confused as to what you meant.