# 在Ruby中映射两个数组的值

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

0

## 6 答案

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

``````weights.zip(data).inject(0) {|sum,(w,d)| sum + w*d }
``````
0

``````weights = [1,2,3]
data    = [10,50,30]

require 'matrix'
Vector[*weights].inner_product Vector[*data] # => 200
``````
0

@Michiel de Mare

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

``````weights.zip(data).map(&:*).reduce(&:+)
``````
0

@FelixRabe：看起来ruby已经改变了在这类过程中如何处理参数。我真的不知道任何细节，因为几年后我没有碰过红宝石。

Ruby有一个 `map` 方法（a.k.a. `collect` 方法），它可以应用于任何 `Enumerable` 对象。如果 `numbers` 是一个数字数组，Ruby中的以下行：

``````numbers.map{|x| x + 5}
``````

``````map(lambda x: x + 5, numbers)
``````

0

Array.zip函数执行数组的元素组合。它不像Python语法那么干净，但是可以使用以下一种方法：

``````weights = [1, 2, 3]
data = [4, 5, 6]
result = Array.new
a.zip(b) { |x, y| result << x * y } # For just the one operation

sum = 0
a.zip(b) { |x, y| sum += x * y } # For both operations
``````
0

``````def dot(*arrays)
arrays.transpose.map {|vals| yield vals}
end

dot(weights,data) {|a,b| a*b}

# OR, if you have a third array

dot(weights,data,offsets) {|a,b,c| (a*b)+c}
``````

``````class Array
def dot
self.transpose.map{|vals| yield vals}
end
end

[weights,data].dot {|a,b| a*b}

#OR

[weights,data,offsets].dot {|a,b,c| (a*b)+c}
``````
0