Mapping values from 2 array in Ruby

I'm asking yourself if there's a means to do what I can do listed below with Python, in Ruby:

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

I have 2 selections of equivalent dimensions with the weights and also information yet I can not appear to locate a function comparable to map in Ruby, reduce I have functioning.

2019-05-09 11:19:03
Source Share
Answers: 4

In Ruby 1.9:{|a,b| a*b}.reduce(:+)

In Ruby 1.8: {|sum,(w,d)| sum + w*d }
2019-05-13 14:45:25

@Michiel de Mare

Your Ruby 1.9 instance can be reduced a little bit more:*).reduce(:+)

Also keep in mind that in Ruby 1.8, if you call for ActiveSupport (from Rails) you can make use of:*).reduce(&:+)
2019-05-13 14:41:48

Ruby has a map method (a.k.a. the collect method), which can be related to any kind of Enumerable object. If numbers is an array of numbers, the adhering to line in Ruby:{|x| x + 5}

is the matching of the adhering to line in Python:

map(lambda x: x + 5, numbers)

For even more information, see here or here.

2019-05-12 02:47:35

The function does an elementwise mix of selections. It's not fairly as tidy as the Python syntax, yet below is one strategy you can make use of:

weights = [1, 2, 3]
data = [4, 5, 6]
result = { |x, y| result << x * y } # For just the one operation

sum = 0 { |x, y| sum += x * y } # For both operations
2019-05-12 02:24:38