Rubyの配列の可変数の製品を検索します
質問
私は配列の可変数から単一の項目のすべての組み合わせを見つけるために探しています。私はRubyでこれを行う方法を教えてください。
二つの配列を考えると、私はこのような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"]]
どのようにできたグループは、配列の変数の数が含まれているこのコードの動作?
解決
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"]
# ]
所属していません StackOverflow