Reason #125 • May 5th, 2026

Chunking collections with Enumerable#each_slice

The Enumerable#each_slice method allows us to iterate over collections in fixed-size chunks or "slices". The method takes an integer argument that specifies the size of each slice and yields each slice to the given block:

Ruby
numbers = [1, 2, 3, 4, 5, 6, 7]
numbers.each_slice(3) do |slice|
  p slice
end
# Output:
# [1, 2, 3]
# [4, 5, 6]
# [7]

# We can also use each_slice to create an array of slices:
slices = numbers.each_slice(3).to_a
# => [[1, 2, 3], [4, 5, 6], [7]]
      
JavaScript
const numbers = [1, 2, 3, 4, 5, 6, 7];
for (let i = 0; i < numbers.length; i += 3) {
  const slice = numbers.slice(i, i + 3);
  console.log(slice);
}
// Output:
// [1, 2, 3]
// [4, 5, 6]
// [7]

// To create an array of slices:
const slices = [];
for (let i = 0; i < numbers.length; i += 3) {
  slices.push(numbers.slice(i, i + 3));
}
// => [[1, 2, 3], [4, 5, 6], [7]]
      

Gotta love Enumerable ❤️

History

Enumerable#each_slice started life in the old enumerator extension, added in Ruby 1.8.1, released in 2003. At that point it was something you got by requiring the extension rather than a method baked into core Enumerable from the start.

In Ruby 1.8.7, released in May 2008, the enumerator library became built in, and each_slice became available as one of the standard Enumerable methods. Around the same time it also settled into the modern no-block behavior: numbers.each_slice(3) returns an Enumerator, which is what makes numbers.each_slice(3).to_a work.

Reason #126 ?