End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Enumerable#each_cons
each_cons(n) { ... } → self
each_cons(n) → enumerator
enum.c
View on GitHub ↗
static VALUE
enum_each_cons(VALUE obj, VALUE n)
{
long size = NUM2LONG(n);
struct MEMO *memo;
int arity;
if (size <= 0) rb_raise(rb_eArgError, "invalid size");
RETURN_SIZED_ENUMERATOR(obj, 1, &n, enum_each_cons_size);
arity = rb_block_arity();
if (enum_size_over_p(obj, size)) return obj;
memo = MEMO_NEW(rb_ary_new2(size), dont_recycle_block_arg(arity), size);
rb_block_call(obj, id_each, 0, 0, each_cons_i, (VALUE)memo);
return obj;
}
Calls the block with each successive overlapped n-tuple of elements; returns self:
Example
a = [] (1..5).each_cons(3) {|element| a.push(element) } a # => [[1, 2, 3], [2, 3, 4], [3, 4, 5]] a = [] h = {foo: 0, bar: 1, baz: 2, bam: 3} h.each_cons(2) {|element| a.push(element) } a # => [[[:foo, 0], [:bar, 1]], [[:bar, 1], [:baz, 2]], [[:baz, 2], [:bam, 3]]]
With no block given, returns an Enumerator.
Ruby version changes
-
3.1
-
Enumerable#each_consand each_slice to return a receiver. [GH-1509]Example[1, 2, 3].each_cons(2){} # 3.0 => nil # 3.1 => [1, 2, 3] [1, 2, 3].each_slice(2){} # 3.0 => nil # 3.1 => [1, 2, 3]
-