gpt4 book ai didi

ruby - 为什么我的 block 只执行一次?

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

为什么会这样:

array = (1..20).to_a
array.index.each_slice(5) do |slice|
puts slice.inspect
end

返回:

[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
[11, 12, 13, 14, 15]
[16, 17, 18, 19, 20]

同时:

other_array = []
array = (1..20).to_a
array.index.each_slice(5) do |slice|
puts slice.inspect
other_array.push(1)
end

仅返回:

[1, 2, 3, 4, 5]

other_array.push(1) 如何中断 block 的执行?一个明显的结论是我无法访问不在 block 范围内的变量,但这是为什么呢?

最佳答案

我在数组文档中找到了解决方案。我想知道您为什么要对数组使用 index 函数,而您似乎只想遍历数组。为此,您可以使用 array.each_slice 而无需调用索引。索引如下:http://ruby-doc.org/core-2.2.0/Array.html#method-i-index

Returns the index of the first object in ary such that the object is == to obj.

If a block is given instead of an argument, returns the index of the first object for which the block returns true. Returns nil if no match is found

因此您的代码会评估 block 并检查结果是否为 true。在第一个示例中,您只执行了一个返回 nilputs。无为假。
第二个示例返回包含单个 1 的数组对象。
在 ruby​​ 中,每个条件都是 true,如果不是 falsenil。你可以在这里看到:

if nil
puts "foo"
end
=> nil

other_array = [1]
if other_array
puts "foo"
end
=> "foo"

所以你的第二个例子中的 block 返回了一些非假的东西,所以它不会再次运行,因为它找到了一个“有效”的结果。

对于返回,您可能应该知道,如果没有给出其他返回,ruby 会返回任何范围内的最后一个表达式。所以它返回 other_array。如果您不想重新格式化您的代码,您可以执行以下操作:

other_array = []
array = (1..20).to_a
array.index.each_slice(5) do |slice|
puts slice.inspect
other_array.push(1)
nil
end

这将强制 block 返回 nil 并且迭代将起作用。

关于ruby - 为什么我的 block 只执行一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38188288/

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