gpt4 book ai didi

ruby - Ruby 1.8.5 中是否有 Array#each_slice() 的等价物?

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

我正在使用 ruby​​ 1.8.5,数组的 each_slice() 方法不起作用。

我的代码是这样的:

array.each_slice(3) do |name,age,sex|   .....   end

有没有其他方法可以在我的旧版 ruby​​ 中实现相同的功能。

最佳答案

自己烤

module Enumerable
def each_slice( n )
res = []
self.each do |el|
res << el
if res.size == n then
yield res.dup
res.clear
end
end
yield res.dup unless res.empty?
end
end

关于ruby - Ruby 1.8.5 中是否有 Array#each_slice() 的等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6095616/

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