How to Use each_slice in Ruby: Simple Guide with Examples
In Ruby,
each_slice is an Enumerable method that splits a collection into smaller groups of a specified size and processes each group one by one. You use it by calling each_slice(n) on an array or enumerable, where n is the size of each group, and provide a block to handle each slice.Syntax
The each_slice method is called on an enumerable object like an array. It takes one argument, the size of each slice, and a block that receives each slice as an array.
enumerable.each_slice(n) { |slice| ... }nis the number of elements in each group.- The block runs once for each slice, receiving an array of
nelements (except possibly the last slice).
ruby
array = [1, 2, 3, 4, 5, 6] array.each_slice(2) do |slice| puts "Slice: #{slice.inspect}" end
Output
Slice: [1, 2]
Slice: [3, 4]
Slice: [5, 6]
Example
This example shows how to use each_slice to process an array of numbers in groups of 3 and print each group.
ruby
numbers = (1..10).to_a numbers.each_slice(3) do |group| puts "Group: #{group.join(', ')}" end
Output
Group: 1, 2, 3
Group: 4, 5, 6
Group: 7, 8, 9
Group: 10
Common Pitfalls
One common mistake is expecting each_slice to return an array of slices. Instead, it returns an Enumerator if no block is given. Another pitfall is not handling the last slice which may have fewer elements than the specified size.
Also, calling each_slice on a non-enumerable object will cause an error.
ruby
# Wrong: expecting an array result result = [1, 2, 3, 4].each_slice(2) puts result.inspect # => Enumerator, not array # Right: convert to array if needed result = [1, 2, 3, 4].each_slice(2).to_a puts result.inspect # => [[1, 2], [3, 4]]
Output
# Output of first puts:
# #<Enumerator: [1, 2, 3, 4]:each_slice(2)>
# Output of second puts:
# [[1, 2], [3, 4]]
Quick Reference
| Usage | Description |
|---|---|
| each_slice(n) { |slice| ... } | Processes elements in groups of n, running the block for each slice. |
| each_slice(n).to_a | Returns an array of slices, each slice is an array of n elements. |
| Enumerator without block | Returns an Enumerator if no block is given, allowing chaining or conversion. |
| Last slice size | May be smaller than n if total elements are not divisible by n. |
Key Takeaways
Use each_slice(n) to process enumerable elements in groups of size n.
Provide a block to handle each slice as an array of elements.
If no block is given, each_slice returns an Enumerator.
The last slice may have fewer elements if the total count isn't divisible by n.
Convert to array with to_a if you want all slices at once.
