Skip to content

End of Life Ruby 3.2 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

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.

See also #one? #reduce #none? #reject also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0