Product Search with Variable Ruby Arrays

I am looking to find all combinations of individual elements from among variable arrays. How to do it in Ruby?

Given two arrays, I can use Array.product as follows:

groups = [] groups[0] = ["hello", "goodbye"] groups[1] = ["world", "everyone"] combinations = groups[0].product(groups[1]) puts combinations.inspect # [["hello", "world"], ["hello", "everyone"], ["goodbye", "world"], ["goodbye", "everyone"]] 

How can this code work when groups contain a variable number of arrays?

+7
ruby loops product depth
source share
1 answer
 groups = [ %w[hello goodbye], %w[world everyone], %w[here there] ] combinations = groups.first.product(*groups.drop(1)) p combinations # [ # ["hello", "world", "here"], # ["hello", "world", "there"], # ["hello", "everyone", "here"], # ["hello", "everyone", "there"], # ["goodbye", "world", "here"], # ["goodbye", "world", "there"], # ["goodbye", "everyone", "here"], # ["goodbye", "everyone", "there"] # ] 
+13
source share

All Articles