Enumerable#partition for fun & profit
Ruby’s Enumerable#partition
method is one of those hidden gems that can dramatically simplify your Rails code. This method splits any enumerable collection into two arrays based on a block condition, returning both the elements that match the condition and those that don’t in a single operation. Instead of filtering your data multiple times or writing lengthy conditional logic, partition handles the separation in one clean pass through your collection.
In Rails applications, partition shines when you need to categorize records or separate valid from invalid data. Consider a scenario where you’re processing user uploads and need to separate successful from failed imports, or when you want to split a collection of orders into paid and unpaid categories. Rather than calling select
twice (which iterates through your collection twice), partition does both operations simultaneously. For example, orders.partition(&:paid?)
instantly gives you both paid and unpaid orders in separate arrays, making your code both faster and more expressive.
The real beauty of partition becomes apparent in controller actions and service objects where you often need to handle success and failure cases differently. Whether you’re bulk updating records, processing API responses, or separating active from inactive users, partition eliminates the need for temporary variables and multiple iterations. This method transforms what could be several lines of filtering logic into a single, self-documenting operation that clearly communicates your intent while keeping your Rails applications lean and performant.