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.
This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).
Array#&() is a Array class method which performs set intersection operation on the arrays. And returns the common of the two arrays. Parameter: Arrays for performing the intersection operation.
Map is a Ruby method that you can use with Arrays, Hashes & Ranges. The main use for map is to TRANSFORM data. For example: Given an array of strings, you could go over every string & make every character UPPERCASE.
The map() of enumerable is an inbuilt method in Ruby returns a new array with the results of running block once for every element in enum.
@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(&:+)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With