Finding the product of a variable number of Ruby arrays

前端 未结 1 1158
遥遥无期
遥遥无期 2021-01-05 09:07

I\'m looking to find all combinations of single items from a variable number of arrays. How do I do this in Ruby?

Given two arrays, I can use Array.product like this

相关标签:
1条回答
  • 2021-01-05 09:32
    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"]
    # ]
    
    0 讨论(0)
提交回复
热议问题