gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:15:57 25 4
gpt4 key购买 nike

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

最佳答案

“产生所有组合”意味着它将产生(提供)目标(自身)和其他(参数)数组中元素的所有组合给给定的 block 。

例如:

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

大致相当于这个函数:

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

关于给定 block 时的 Ruby Array#product 方法行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29309349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com