Method: Enumerable#partition

Defined in:
enum.c

#partition {|element| ... } ⇒ Array #partitionObject

With a block given, returns an array of two arrays:

  • The first having those elements for which the block returns a truthy value.

  • The other having all other elements.

Examples:

p = (1..4).partition {|i| i.even? }
p # => [[2, 4], [1, 3]]
p = ('a'..'d').partition {|c| c < 'c' }
p # => [["a", "b"], ["c", "d"]]
h = {foo: 0, bar: 1, baz: 2, bat: 3}
p = h.partition {|key, value| key.start_with?('b') }
p # => [[[:bar, 1], [:baz, 2], [:bat, 3]], [[:foo, 0]]]
p = h.partition {|key, value| value < 2 }
p # => [[[:foo, 0], [:bar, 1]], [[:baz, 2], [:bat, 3]]]

With no block given, returns an Enumerator.

Related: Enumerable#group_by.

Overloads:

  • #partition {|element| ... } ⇒ Array

    Yields:

    • (element)

    Returns:



1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
# File 'enum.c', line 1137

static VALUE
enum_partition(VALUE obj)
{
    struct MEMO *memo;

    RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);

    memo = MEMO_NEW(rb_ary_new(), rb_ary_new(), 0);
    rb_block_call(obj, id_each, 0, 0, partition_i, (VALUE)memo);

    return rb_assoc_new(memo->v1, memo->v2);
}