End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Enumerable#chunk_while
chunk_while {|element, next_element| ... } → enumerator
enum.c
View on GitHub ↗
static VALUE
enum_chunk_while(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, Qtrue);
rb_block_call(enumerator, idInitialize, 0, 0, slicewhen_i, enumerator);
return enumerator;
}
The returned Enumerator uses the block to partition elements into arrays (“chunks”); it calls the block with each element and its successor; begins a new chunk if and only if the block returns a truthy value:
Example:
Example
a = [1, 2, 4, 9, 10, 11, 12, 15, 16, 19, 20, 21] e = a.chunk_while {|i, j| j == i + 1 } e.each {|array| p array }
Output:
Example
[1, 2] [4] [9, 10, 11, 12] [15, 16] [19, 20, 21]