# 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.

In Ruby 1.9:

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

In Ruby 1.8:

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

@Michiel de Mare

Your Ruby 1.9 instance can be reduced a little bit more:

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

Also keep in mind that in Ruby 1.8, if you call for ActiveSupport (from Rails) you can make use of:

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

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:

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

is the matching of the adhering to line in Python:

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

The Array.zip 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 = 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
```

Related questions