Paginate An Array In Ruby Using Each_slice
When displaying large datasets in pages — or processing records in batches — you need to split an array into fixed-size chunks. Ruby’s each_slice handles this cleanly without manual index arithmetic.
Description
Enumerable#each_slice(n) yields sub-arrays of size n in sequence. The last chunk may be smaller if the total count isn’t evenly divisible.
Combined with a page number and page size, you can implement pagination without any gem. This pattern is useful for batching API calls, processing CSV rows in chunks, or building a manual pagination layer over an in-memory collection.
Sample input:
items = (1..25).to_a
page = 2
per_page = 10
Sample Output:
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Answer
def paginate(array, page:, per_page:)
array.each_slice(per_page).to_a[page - 1] || []
end
items = (1..25).to_a
paginate(items, page: 1, per_page: 10) # => [1..10]
paginate(items, page: 2, per_page: 10) # => [11..20]
paginate(items, page: 3, per_page: 10) # => [21, 22, 23, 24, 25]
paginate(items, page: 4, per_page: 10) # => []
# Process in batches without page numbers
items.each_slice(10) do |batch|
process_batch(batch)
end
Check viewARU - Brand Newsletter!
Newsletter to DEVs by DEVs - boost your Personal Brand & career! 🚀