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.
@Michiel de Mare
Your Ruby 1.9 example can be shortened a bit further:
Also note that in Ruby 1.8, if you require ActiveSupport (from Rails) you can use:
In Ruby 1.9:
In Ruby 1.8:
The Array.zip function does an elementwise combination of arrays. It's not quite as clean as the Python syntax, but here's one approach you could use:
Ruby has a
map
method (a.k.a. thecollect
method), which can be applied to anyEnumerable
object. Ifnumbers
is an array of numbers, the following line in Ruby:is the equivalent of the following line in Python:
For more details, see here or here.
An alternative for the map that works for more than 2 arrays as well:
This could also be added to Array: