给定块时Ruby Array#product方法的行为

nzh*_*nry 5 ruby

在Ruby中,给定块时Array#product方法会做什么?文档说:“如果给出一个块,产品将产生所有组合并返回自身。” 产生所有组合是什么意思?该方法对给定的块有什么作用?

mae*_*ics 5

“产生所有组合”意味着将产生(供应)目标(自身)和其他(自变量)数组中元素的所有组合到给定块。

例如:

a = [1, 2]
b = [:foo, :bar]
a.product(b) { |x| puts x.inspect } # => [1, 2]
# [1, :foo]
# [1, :bar]
# [2, :foo]
# [2, :bar]
Run Code Online (Sandbox Code Playgroud)

它大致等效于以下功能:

class Array
  def yield_products(other)
    self.each do |x|
      other.each do |y|
        yield [x, y] if block_given?
      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)