Home > Enterprise >  Ruby: how to split a collection by predicate into two collections in ruby?
Ruby: how to split a collection by predicate into two collections in ruby?

Time:02-03

I need to separate the elements of a single collection by some predicate into two collections, one containing the YES-elements, the other containing to NO-elements.
I want to do that in only one iteration and I want to avoid temporary copies.
The following works for me:

irb> aaa = [ 1, 2, 3, 4 ,5, 6, 7, 8, 9 ]; bbb = [];
irb> aaa.reject!{|n| bbb<<n unless n.odd? }
irb> bbb
 # => [2, 4, 6, 8]
irb> aaa
 # => [1, 3, 5, 7, 9]

but I wonder, is there a better more readable solution AND is there something like this for a Hash?

CodePudding user response:

Use Enumerable#partition:

partition { |obj| block } → [ true_array, false_array ]
partition → an_enumerator

Returns two arrays, the first containing the elements of enum for which the block evaluates to true, the second containing the rest.

irb(main):011:0> (1..10).partition(&:odd?)
=> [[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]
  • Related