Finding the product of a variable number of Ruby a

2019-02-13 16:30发布

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:

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 could this code work when groups contains a variable number of arrays?

1条回答
等我变得足够好
2楼-- · 2019-02-13 16:54
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"]
# ]
查看更多
登录 后发表回答