Array chooses to get true and false arrays?

I know that I can easily do this:

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 way (or an elegant way) to get this just by running selectonce?

[lower_than_50, greater_than_50] = array.split_boolean{ |n| n<50}
+4
source share
2 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 want the result to be like one array with two subarrays.

Editing: as a bonus, here's how you do it if you have more than two alternatives and want to break down 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]}
+9
source

The answer above is in place!

Here is a general solution for more than two sections (for example:) <20, <50, >=50:

arr = [45, 89, 23, 11, 102, 95]
arr.group_by { |i| i < 20 ? 'a' : i < 50 ? 'b' : 'c' }.sort.map(&:last)
=> [[11], [45, 23], [89, 102, 95]]

This can be very useful if you group chunks (or any mathematically computable index such as modulo):

arr.group_by { |i| i / 50 }.sort.map(&:last)
=> [[45, 23, 11], [89, 95], [102]]
0
source

Source: https://habr.com/ru/post/1523917/


All Articles