Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Enumerable#each_slice
(::Integer n) { (::Array[E]) -> void } -> self
(::Integer n) -> ::Enumerator[::Array[E], self]
each_slice(n) { ... } → self
each_slice(n) → enumerator
enum.c
View on GitHub ↗
static VALUE
enum_each_slice(VALUE obj, VALUE n)
{
rb_len_t size = NUM2LEN(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 = rb_imemo_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 obj;
}
Calls the block with each successive disjoint n-tuple of elements; returns self:
Example
a = [] (1..10).each_slice(3) {|tuple| a.push(tuple) } a # => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]] a = [] h = {foo: 0, bar: 1, baz: 2, bat: 3, bam: 4} h.each_slice(2) {|tuple| a.push(tuple) } a # => [[[:foo, 0], [:bar, 1]], [[:baz, 2], [:bat, 3]], [[:bam, 4]]]
With no block given, returns an Enumerator.
See also
#each_entry
#each_with_index
#each_cons
#each_with_object
also in
4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0