Read more

Ruby: Enumerable#partition

Thomas Klemm
March 09, 2015Software engineer

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

# 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]]
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

Works well with destructuring assignment, too.

even, odd = (1..6).partition { |n| n.even? }
even #=> [2, 4, 6]
odd  #=> [1, 3, 5]
Posted by Thomas Klemm to makandra dev (2015-03-09 20:53)