Arnold Roa Arnold Roa - 1 year ago 78
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,
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 Source

Use Enumerable#partition:

a = [1,2,3]
b, c = a.partition { |x| x == 3 } #=> [[3], [1, 2]]
b #=> [3]
c #=> [1, 2]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download