HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

A pattern to destructively extract items from an array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
destructivelyarrayitemsextractfrompattern

Problem

I want to efficiently (few intermediate objects) and neatly (few lines and easy to read) filter an array, removing and returning rejected items. So like a call to delete_if except instead of returning the remaining items, returning the deleted items.

Here's some code that works:

ary = (0..9).to_a
odds = ary.select {|i| i%2==1 }
ary -= odds


or:

ary = (0..9).to_a
(_,ary),(_,odds) = ary.group_by {|i| i.odd? }.sort {|a,b| a[0] ? 1 : -1 }


But I can't help but think there should be a better way...

Ideally something more like: odds = ary.delete_and_return(&:odd?)

Solution

Array.partition returns an array of two arrays - one where the elements returned true to the condition, and one that returned false.

So, a single liner for your need would be:

odds, ary = (0..9).to_a.partition(&:odd?)
=> [[1, 3, 5, 7, 9], [0, 2, 4, 6, 8]]


(&:odd?) acts exactly like writing { |x| x.odd? } which will return true if the number is, well, odd...

Code Snippets

odds, ary = (0..9).to_a.partition(&:odd?)
=> [[1, 3, 5, 7, 9], [0, 2, 4, 6, 8]]

Context

StackExchange Code Review Q#25648, answer score: 4

Revisions (0)

No revisions yet.