0
0
RubyHow-ToBeginner · 3 min read

How to Use chunk Method in Ruby: Syntax and Examples

In Ruby, chunk is an Enumerable method that groups consecutive elements based on the result of a block. It returns an enumerator of pairs where each pair contains the key and an array of grouped elements sharing that key.
📐

Syntax

The chunk method is called on an enumerable object like an array. It takes a block that returns a key for each element. Consecutive elements with the same key are grouped together.

Basic syntax:

enumerable.chunk { |element| key }

This returns an enumerator of [key, array_of_elements] pairs.

ruby
array.chunk { |element| element.even? }
💻

Example

This example groups numbers by whether they are even or odd using chunk. It shows how consecutive elements with the same condition are grouped.

ruby
array = [1, 1, 2, 2, 3, 4, 4, 5]
result = array.chunk { |n| n.even? }.to_a
puts result.inspect
Output
[[false, [1, 1]], [true, [2, 2]], [false, [3]], [true, [4, 4]], [false, [5]]]
⚠️

Common Pitfalls

A common mistake is expecting chunk to group all elements with the same key anywhere in the enumerable. chunk only groups consecutive elements with the same key. If elements with the same key are separated, they form separate groups.

Also, forgetting to convert the enumerator to an array with to_a can cause confusion when printing results.

ruby
array = [1, 2, 1, 2]
# Wrong: expecting one group per key
result = array.chunk { |n| n.even? }.to_a
puts result.inspect

# Output shows separate groups for separated keys
# [[false, [1]], [true, [2]], [false, [1]], [true, [2]]]
Output
[[false, [1]], [true, [2]], [false, [1]], [true, [2]]]
📊

Quick Reference

  • Purpose: Group consecutive elements by a key.
  • Returns: Enumerator of [key, array] pairs.
  • Use: Call to_a to get an array of groups.
  • Note: Groups only consecutive elements with the same key.

Key Takeaways

The chunk method groups consecutive elements sharing the same key returned by the block.
chunk returns an enumerator; use to_a to convert it to an array for easy use.
Only consecutive elements with the same key are grouped together, not all elements with that key.
Use chunk to split data into runs or segments based on a condition.
Remember chunk works on any enumerable, like arrays or ranges.