End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Enumerable#partition
partition {|element| ... } → [true_array, false_array]
partition → enumerator
enum.c
View on GitHub ↗
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);
}
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:
Example
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.