7

可変数の配列から単一アイテムのすべての組み合わせを見つけようとしています。Rubyでこれを行うにはどうすればよいですか?

2 つの配列が与えられた場合、次のように Array.product を使用できます。

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"]]

グループに可変数の配列が含まれている場合、このコードはどのように機能するのでしょうか?

4

1 に答える 1

13
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"]
# ]
于 2010-08-05T23:34:19.203 に答える