Array select to get true and false arrays?
arrays, ruby
Solution
over, under_or_equal = [45, 89, 23, 11, 102, 95].partition{|x| x>50 }
Or simply:
result = array.partition{|x| x>50 }
p result #=> [[89, 102, 95], [45, 23, 11]]
if you rather want the result as one array with two sub-arrays.
Edit: As a bonus, here is how you would to it if you have more than two alternatives and want to split the numbers:
my_custom_grouping = -> x do
case x
when 1..50 then :small
when 51..100 then :large
else :unclassified
end
end
p [-1,2,40,70,120].group_by(&my_custom_grouping) #=> {:unclassified=>[-1, 120], :small=>[2, 40], :large=>[70]}
Problem
I know I can get this easily: ``` array = [45, 89, 23, 11, 102, 95] lower_than_50 = array.select{ |n| n<50} greater_than_50 = array.select{ |n| !n<50} ``` But is there a method (or an elegant manner) to get this by only running `select` once? ``` [lower_than_50, greater_than_50] = array.split_boolean{ |n| n<50} ```