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]