tags:

views:

1082

answers:

5

I'm wondering if there's a way to do what I can do below with Python, in Ruby:

sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data))

I have two arrays of equal sizes with the weights and data but I can't seem to find a function similar to map in Ruby, reduce I have working.

A: 
Curt Hagenlocher
A: 

Ruby has a map method (a.k.a. the collect method), which can be applied to any Enumerable object. If numbers is an array of numbers, the following line in Ruby:

numbers.map{|x| x + 5}

is the equivalent of the following line in Python:

map(lambda x: x + 5, numbers)

For more details, see here or here.

Joey deVilla
A: 

@Joey I guess my problem lies in the fact I can't seem to pass in an array of values using map/collect. In the Python code it's taking TWO arrays and mapping them together with my lambda function. I don't see a way to do that in Ruby...is it possible?

@Curt your answer would work, but I'm really hoping to find an approach more close to the Python example I gave.

Tim Trueman
A: 

In Ruby 1.9:

weights.zip(data).map{|a,b| a*b}.reduce(:+)

In Ruby 1.8:

weights.zip(data).inject(0) {|sum,(w,d)| sum + w*d }
Michiel de Mare
+5  A: 

@Michiel de Mare

Your Ruby 1.9 example can be shortened a bit further:

weights.zip(data).map(:*).reduce(:+)

Also note that in Ruby 1.8, if you require ActiveSupport (from Rails) you can use:

weights.zip(data).map(&:*).reduce(&:+)
Kevin Ballard