如何在 Ruby 中对数组进行分块 [英] How to chunk an array in Ruby

查看:20
本文介绍了如何在 Ruby 中对数组进行分块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 1.8.6 中,我有一个包含 100,000 个用户 ID 的数组,每个 ID 都是一个 int.我想对这些用户 ID 执行一段代码,但我想分块执行.例如,我想一次处理它们 100 个.我怎样才能尽可能轻松地实现这一目标?

In Ruby 1.8.6, I have an array of, say, 100,000 user ids, each of which is an int. I want to perform a block of code on these user ids but I want to do it in chunks. For example, I want to process them 100 at a time. How can I easily achieve this as simply as possible?

我可以执行以下操作,但可能有更简单的方法:

I could do something like the following, but probably there's an easier way:

a = Array.new
userids.each { |userid|
  a << userid
  if a.length == 100
    # Process chunk
    a = Array.new
  end
}
unless a.empty?
  # Process chunk
end

推荐答案

使用 each_slice:

require 'enumerator'
userids.each_slice(100) do |a|
  # do something with a
end

这篇关于如何在 Ruby 中对数组进行分块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆