Posted over 7 years ago. Visible to the public.

Ruby: Enumerable#partition

If you want to sort values from an enumerable into two arrays based on whether they match a certain criteria or not, Enumerable#partition Archive can come in handy.

Copy
# Enumerable#partition returns two arrays, # the first containing the elements of enum # for which the block evaluates to true, # the second containing the rest. (1..6).partition { |v| n.even? } #=> [[2, 4, 6], [1, 3, 5]]

Works well with destructuring assignment, too.

Copy
even, odd = (1..6).partition { |n| n.even? } even #=> [2, 4, 6] odd #=> [1, 3, 5]

Your development team has a full backlog of feature requests, chores and refactoring coupled with deadlines? We are familiar with that. With our "DevOps as a Service" offering, we support developer teams with infrastructure and operations expertise.

Owner of this card:

Avatar
Thomas Klemm
Last edit:
over 7 years ago
by Thomas Klemm
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Thomas Klemm to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more