Cross Product in Ruby with Array

I was digging around the Ruby standard library on Enumerable and Arrays to find if there was a method to get the cross product of two arrays in Ruby and found Array.product.

I was showing the code that used this to another teammate and they didn’t realize what the product method was doing, and upon telling them it returns the cross product of two arrays, he was pleasantly surprised to hear about it, so I realized I should share this for anyone else who may not know about it.

Below is an example usage of the product method, and more can be found on the ruby-doc site for Array.

[1] pry(main)> [1, 2, 3, 4, 5].product [:a, :b, :c]
=> [[1, :a],
 [1, :b],
 [1, :c],
 [2, :a],
 [2, :b],
 [2, :c],
 [3, :a],
 [3, :b],
 [3, :c],
 [4, :a],
 [4, :b],
 [4, :c],
 [5, :a],
 [5, :b],
 [5, :c]]
[2] pry(main)> 

Hope someone else can find this useful as well.

–Proctor