Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Array#product method behaviour when given a block

Tags:

ruby

In Ruby, what does the Array#product method do when given a block? The documentation says "If given a block, product will yield all combinations and return self instead." What does it mean to yield all combinations? What does the method do with the given block?

like image 474
nzhenry Avatar asked Mar 27 '15 20:03

nzhenry


1 Answers

By "yield all combinations" it means that it will yield (supply) all combinations of elements in the target (self) and other (argument) arrays to the given block.

For example:

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

It is roughly equivalent to this function:

class Array
  def yield_products(other)
    self.each do |x|
      other.each do |y|
        yield [x, y] if block_given?
      end
    end
  end
end
like image 101
maerics Avatar answered Sep 30 '22 06:09

maerics