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- Expected output: [2, 8, 4] [5, 1]
- 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