views:

460

answers:

3

Hi ,

What is the ruby way to achieve following? Thanks.

a = [1,2]
b = [3,4]

I want an array: 
=> [f(1,3) ,f(1,4) , f(2,3) ,f(2,4)]

EDIT:

Sepp2k's way is very clever and impressive but Aaron used build-in function. I accept the build-in method as the answer. Thanks you all!

+3  A: 
a.map {|x| b.map {|y| f(x,y) } }.flatten

Note: On 1.8.7+ you can add 1 as an argument to flatten, so you'll still get correct results when f returns an array.

Here's an abstraction for an arbitrary amount of arrays:

def combine_arrays(*arrays)
  if arrays.empty?
    yield
  else
    first, *rest = arrays
    first.map do |x|
      combine_arrays(*rest) {|*args| yield x, *args }
    end.flatten
      #.flatten(1)
  end
end

combine_arrays([1,2,3],[3,4,5],[6,7,8]) do |x,y,z| x+y+z end
# => [10, 11, 12, 11, 12, 13, 12, 13, 14, 11, 12, 13, 12, 13, 14, 13, 14, 15, 12, 13, 14, 13, 14, 15, 14, 15, 16]
sepp2k
This will work though I'm not sure if it is the best way (though can't think of a better one so +1)
Robert Massaioli
I wish I could +2 for the combination of arbitrary amount of arrays. Very cool!
pierr
+8  A: 

You can use product to get the cartesian product of the arrays first, then collect the function results.

a.product(b) => [[1, 3], [1, 4], [2, 3], [2, 4]]

So you can use map or collect to get the results. They are different names for the same method.

a.product(b).collect { |x, y| f(x, y) }
Aaron Hinni
Product is only built-in as of 1.9.
Pesto
Product is in 1.8.7 - I use it to do exactly what Pierr is asking
Chris McCauley
+2  A: 

Facets has Array#product which will give you the cross product of arrays. It is also aliased as the ** operator for the two-array case. Using that, it would look like this:

require 'facets/array'
a = [1,2]
b = [3,4]

(a.product(b)).collect {|x, y| f(x, y)}

If you are using Ruby 1.9, product is a built-in Array function.

Pesto