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
enum.c
View on GitHub ↗
static VALUE
enum_slice_when(VALUE enumerable)
{
VALUE enumerator;
VALUE pred;
pred = rb_block_proc();
enumerator = rb_obj_alloc(rb_cEnumerator);
rb_ivar_set(enumerator, id_slicewhen_enum, enumerable);
rb_ivar_set(enumerator, id_slicewhen_pred, pred);
rb_ivar_set(enumerator, id_slicewhen_inverted, Qfalse);
rb_block_call(enumerator, idInitialize, 0, 0, slicewhen_i, enumerator);
return 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]