← All languages
image/svg+xml
Ruby method of the day

each_slice

Iterate over consecutive slices of the given size.

Description

The each_slice method divides the collection into consecutive slices of the given size and iterates over each slice. The last slice may contain fewer elements if the collection is not evenly divisible.

Without a block, it returns an Enumerator. This method is part of the Enumerable module and is useful for batch processing, pagination, or chunking data into fixed-size groups.

For grouping based on a condition rather than fixed size, use chunk or slice_when instead.

Arguments

NameDescriptionOptional
n The size of each slice. No
{ |slice| ... } A block to execute for each slice. Yes

Example

[1, 2, 3, 4, 5].each_slice(2).to_a   # [[1, 2], [3, 4], [5]]
(1..9).each_slice(3) { |s| p s }
# [1, 2, 3]
# [4, 5, 6]
# [7, 8, 9]

Reference