Jese Leos

Still Learning While Using AI To Code - Or, Enumerable#chunk_while

For someone who thoroughly enjoys the Ruby language, one of the more rewarding aspects of using tools like Cursor and Supermaven has been exposure to some interesting Ruby methods I have not seen before.

Today, it was Enumerable#chunk_while.

The docs say:

Creates an enumerator for each chunked elements. The beginnings of chunks are defined by the block. This method splits each chunk using adjacent elements, elt_before and elt_after, in the receiver enumerator. This method split chunks between elt_before and elt_after where the block returns false. The block is called the length of the receiver enumerator minus one

Yes, that meant nothing to me as well. But here is a sample that should help. Let's take a grocery list in JSON and group all the items by the aisle they are found.

# Sample grocery shopping list
shopping_list = [
  { aisle: 'Produce', item: 'Apples' },
  { aisle: 'Produce', item: 'Bananas' },
  { aisle: 'Dairy', item: 'Milk' },
  { aisle: 'Dairy', item: 'Cheese' },
  { aisle: 'Canned Goods', item: 'Chickpeas' },
  { aisle: 'Canned Goods', item: 'Tomato Sauce' },
  { aisle: 'Snacks', item: 'Chips' },
]

chunked_items = shopping_list.chunk_while do |item1, item2|
  item1[:aisle] == item2[:aisle]
end

grouped_items = chunked_items.map do |aisle_group|
  {
    aisle: aisle_group.first[:aisle],
    items: aisle_group.map { |item| item[:item] }
  }
end

In the end, we have an array that looks like this:

[
 {:aisle=>"Produce", :items=>["Apples", "Bananas"]}
 {:aisle=>"Dairy", :items=>["Milk", "Cheese"]}
 {:aisle=>"Canned Goods", :items=>["Chickpeas", "Tomato Sauce"]}
 {:aisle=>"Snacks", :items=>["Chips"]}
]