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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With