Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chunk an array in Ruby

Tags:

arrays

ruby

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 
like image 882
ChrisInEdmonton Avatar asked Aug 04 '09 22:08

ChrisInEdmonton


People also ask

How do you split an array in Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.

What is array chunking?

The array_chunk() function is an inbuilt function in PHP which is used to split an array into parts or chunks of given size depending upon the parameters passed to the function. The last chunk may contain fewer elements than the desired size of the chunk.

How do you select an array in Ruby?

Ruby | Array select() function Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.

What does .first mean in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.


2 Answers

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 
like image 69
sepp2k Avatar answered Sep 29 '22 05:09

sepp2k


Rails has in_groups_of, which under the hood uses each_slice.

userids.in_groups_of(100){|group|   //process group } 
like image 21
wombleton Avatar answered Sep 29 '22 06:09

wombleton