Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply each item in an array by each item in another array

Tags:

arrays

ruby

In Ruby, how can one multiply every element in one array by every element in another array, such that:

a = [1,2,3]

b = [4,5,6]

c = a*b = [4,5,6,8,10,12,12,15,18]
like image 341
KGSoloman Avatar asked Dec 08 '22 13:12

KGSoloman


1 Answers

For a nice abstraction, can get cartesian product using product:

a.product(b).map { |aa, bb| aa * bb }
like image 122
Amadan Avatar answered Mar 01 '23 23:03

Amadan