Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array select to get true and false arrays?

Tags:

arrays

ruby

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}
like image 645
Augustin Riedinger Avatar asked Jan 12 '23 08:01

Augustin Riedinger


1 Answers

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]}
like image 95
hirolau Avatar answered Jan 18 '23 01:01

hirolau