0
0
RubyHow-ToBeginner · 3 min read

How to Chunk an Array in Ruby: Simple Guide

In Ruby, you can split an array into smaller arrays (chunks) using the each_slice method from the Enumerable module. For example, array.each_slice(3).to_a divides the array into chunks of 3 elements each.
📐

Syntax

The main method to chunk an array in Ruby is each_slice(n), where n is the size of each chunk. It returns an Enumerator that yields slices of the array with n elements.

You can convert this Enumerator to an array of arrays by calling to_a.

ruby
array.each_slice(n).to_a
💻

Example

This example shows how to split an array of numbers into chunks of 3 elements each using each_slice. The result is an array of smaller arrays.

ruby
array = [1, 2, 3, 4, 5, 6, 7, 8]
chunks = array.each_slice(3).to_a
puts chunks.inspect
Output
[[1, 2, 3], [4, 5, 6], [7, 8]]
⚠️

Common Pitfalls

A common mistake is to try using chunk method expecting it to split the array into fixed-size parts. However, chunk groups elements by a condition and is not for fixed-size chunks.

Also, forgetting to convert the Enumerator to an array with to_a can cause unexpected results.

ruby
array = [1, 2, 3, 4, 5]
# Wrong: chunk groups by condition, not size
result = array.chunk { |x| x < 3 }.to_a
puts result.inspect

# Right: use each_slice for fixed-size chunks
result = array.each_slice(2).to_a
puts result.inspect
Output
[[true, [1, 2]], [false, [3, 4, 5]]] [[1, 2], [3, 4], [5]]
📊

Quick Reference

  • each_slice(n): Splits array into chunks of size n.
  • to_a: Converts Enumerator to array.
  • chunk: Groups elements by condition, not size.

Key Takeaways

Use each_slice(n).to_a to split an array into chunks of size n.
The chunk method is for grouping by condition, not fixed-size chunks.
Always convert the Enumerator returned by each_slice to an array with to_a.
Chunks may have fewer elements if the array size isn't divisible by chunk size.
This method works on any Enumerable, including arrays.