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

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

问题描述

在Ruby 1.8.6中,我有一个100,000个用户ID的数组,每个用户ID是一个i​​nt.我想在这些用户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天全站免登陆