1 min read

TIL: Ruby slice_when

Slicing arrays cleverly
TIL: Ruby slice_when
Photo by Ivan Torres / Unsplash

Let's imagine I have an array of stuff...

arr = ['marker', 1, 2, 3, 'marker', 4, 'marker', 5, 6, 7]

I want to chop the array up into smaller arrays everytime I hit a 'marker'.

slices = arr.slice_when { |element, next_element| next_element == 'marker' }

Enumerator#slice_when is lazy so let's force it to see what it's done...

slices.to_a
# => [["marker", 1, 2, 3], ["marker", 4], ["marker", 5, 6, 7]]

Also see Enumerator#slice_after and Enumerator#slice_before.