查找可变数量的Ruby数组的产品

Oll*_*ass 7 ruby loops product depth

我希望从可变数量的数组中找到单个项目的所有组合.我如何在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"]]
Run Code Online (Sandbox Code Playgroud)

当组包含可变数量的数组时,此代码如何工作?

Jör*_*tag 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"]
# ]
Run Code Online (Sandbox Code Playgroud)

  • 它是如何工作的:`product`需要你应用的许多数组,并给出接收器的笛卡尔积和所有参数.splat运算符将一个数组"扩展"为一个参数列表,因此除了first之外,我们将所有数组都放在`groups`中,并将它们作为参数传递给`product`. (5认同)
  • 对实际操作的解释也会有所帮助,并可能导致更好地设计OP的代码...... (2认同)