How to chunk an array in Ruby

RubyArrays

Ruby Problem Overview


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

Ruby Solutions


Solution 1 - Ruby

Use each_slice:

require 'enumerator' # only needed in ruby 1.8.6 and before
userids.each_slice(100) do |a|
  # do something with a
end

Solution 2 - Ruby

Rails has in_groups_of, which under the hood uses each_slice.

userids.in_groups_of(100){|group|
  //process group
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChrisInEdmontonView Question on Stackoverflow
Solution 1 - Rubysepp2kView Answer on Stackoverflow
Solution 2 - RubywombletonView Answer on Stackoverflow