# 从Ruby中的两个数组映射值Mapping values from two array in Ruby

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

## 6 个回复6

### ===============>>#1 票数：14 已采纳

@Michiel de Mare

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

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

### ===============>>#2 票数：5

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

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

### ===============>>#3 票数：2

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
``````

### ===============>>#4 票数：1

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

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

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

### ===============>>#5 票数：0

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

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

### ===============>>#6 票数：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}
``````