Arnold Roa Arnold Roa - 12 days ago 7
Ruby Question

create two arrays bassed on what meet a condition and the diff

Lets suppose I've the follow array:

a = [1,2,3]


I want to split it in two arrays from it, one with items for which a condition is true, and other for which the same condition is false:

b, c = a.split_in_two_arrays_or_something_like_that {|x| x == 3}
#=> b = [3]
#=> c = [1,2]


How can I do that in ruby? I don't want to repeat code with something like:

b = a.reject {|x| x == 3}
c = a.reject {|x| x != 3}


Nor iterate over the array twice.

Is there some method that return me something different than the modified array? For example,
delete_if
will work if it would return the deleted elements, but the original array would've keeped the same, but it doesn't work that way.

Answer

Use Enumerable#partition:

a = [1,2,3]
b, c = a.partition { |x| x == 3 } #=> [[3], [1, 2]]
b #=> [3]
c #=> [1, 2]