End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Enumerable#each_slice
enum.each_slice(n) { ... } → nil
enum.each_slice(n) → an_enumerator
enum.c
View on GitHub ↗
static VALUE
enum_each_slice(VALUE obj, VALUE n)
{
long size = NUM2LONG(n);
VALUE ary;
struct MEMO *memo;
int arity;
if (size <= 0) rb_raise(rb_eArgError, "invalid slice size");
RETURN_SIZED_ENUMERATOR(obj, 1, &n, enum_each_slice_size);
size = limit_by_enum_size(obj, size);
ary = rb_ary_new2(size);
arity = rb_block_arity();
memo = MEMO_NEW(ary, dont_recycle_block_arg(arity), size);
rb_block_call(obj, id_each, 0, 0, each_slice_i, (VALUE)memo);
ary = memo->v1;
if (RARRAY_LEN(ary) > 0) rb_yield(ary);
return Qnil;
}
Iterates the given block for each slice of <n> elements. If no block is given, returns an enumerator.
Example
(1..10).each_slice(3) { |a| p a } # outputs below [1, 2, 3] [4, 5, 6] [7, 8, 9] [10]
See also
#each_entry
#each_with_index
#each_cons
#each_with_object
also in
4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1