Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping values from two array in Ruby

Tags:

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.

like image 319
Tim Trueman Avatar asked Aug 06 '08 11:08

Tim Trueman


People also ask

How do I merge two arrays in Ruby?

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

How do you find the intersection of two arrays in Ruby?

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.

What does .MAP do Ruby?

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.

Does map return a new array Ruby?

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.


1 Answers

@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(&:+) 
like image 121
Lily Ballard Avatar answered Oct 06 '22 09:10

Lily Ballard