Enumerable.each_slice / each_cons / chunk / zip
Advanced iteration methods for splitting a collection into fixed-size groups or combining multiple elements together.
Syntax
# Iterates in groups of n elements.
collection.each_slice(n) { |group| process }
# Iterates over a sliding window of n consecutive elements.
collection.each_cons(n) { |group| process }
# Splits into chunks based on the return value of the block.
collection.chunk { |element| key }
# Combines multiple arrays by matching index.
array1.zip(array2, array3)
Methods
| Method | Description |
|---|---|
| each_slice | Iterates in groups of n elements. The last group may contain fewer than n elements. |
| each_cons | Iterates over a sliding window of n consecutive elements. |
| chunk | Groups consecutive elements by the block's return value and returns an enumerator. |
| zip | Returns an array of arrays, each containing elements at the corresponding index. |
Sample Code
numbers = [1, 2, 3, 4, 5, 6, 7]
# Process in groups of 3 using each_slice.
numbers.each_slice(3) { |group| puts group.inspect }
# [1, 2, 3]
# [4, 5, 6]
# [7]
# Get every 3 consecutive elements using each_cons.
numbers.each_cons(3) { |group| puts group.inspect }
# [1, 2, 3]
# [2, 3, 4]
# [3, 4, 5]
# [4, 5, 6]
# [5, 6, 7]
# Group consecutive identical values using chunk.
data = [1, 1, 2, 2, 2, 1, 3, 3]
data.chunk { |n| n }.each do |key, group|
puts "#{key}: #{group.inspect}"
end
# Pair two arrays together using zip.
names = ["Tanaka", "Yamada", "Suzuki"]
scores = [85, 92, 78]
names.zip(scores).each { |n, s| puts "#{n}: #{s}" }
Notes
each_slice is useful for pagination and batch processing, while each_cons is well-suited for calculating moving averages or comparing consecutive elements. Both methods return an Enumerator when called without a block.
zip is convenient when you want to process multiple arrays in parallel. If a corresponding element does not exist, nil is used as a placeholder, so be careful when the arrays have different lengths. chunk groups adjacent elements that share the same attribute, and unlike group_by, it only groups elements that are next to each other.
If you find any errors or copyright issues, please contact us.