Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Enumerable#slice_when

slice_when {|element, next_element| ... } → enumerator

The returned enumerator uses the block to partition elements into arrays (“slices”); it calls the block with each element and its successor; begins a new slice if and only if the block returns a truthy value:

Example
a = [0, 1, 2, 4, 5, 6, 8, 9]
e = a.slice_when {|i, j| j != i + 1 }
e.each {|array| p array }

Output:

Example
[0, 1, 2]
[4, 5, 6]
[8, 9]
See also #slice_before #sort #slice_after #sort_by also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0