Codectionary / Developer documentation / Ruby

Splitting with partition

partition traverses a collection and returns two arrays: items for which the block is truthy, followed by the remaining items. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

Syntax

matching, remaining = items.partition { |item| condition }

Examples

Splitting with partition

Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

numbers = [5, 2, 8, 1, 4]
even, odd = numbers.partition { |n| n.even? }
p even
p odd
  1. Expected output: [2, 8, 4] [5, 1]
  2. Both arrays preserve encounter order. Destructuring makes the meaning of the true and false partitions explicit.

Best practices

  • Use descriptive variable names for both partitions.
  • Choose select when only the matching side is needed.

Runtime & versions

Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Ruby documentation

Specifications & further reading