Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split an array in ruby based on some condition

I have an array named @level1 which has a value like this:

[   [3.1, 4],   [3.0, 7],   [2.1, 5],   [2.0, 6],   [1.9, 3] ] 

I want to split this into two arrays such that the first array (@arr1) contains the values till 2.1 and the second array (@arr2) contains values after it.

After doing that, I would reverse-sort my second array by doing something like this:

@arr2 = @arr2.sort_by { |x, _| x }.reverse 

I would then like to merge this array to @arr1. Can someone help me how to split the array and then merge them together?

like image 503
Pi Horse Avatar asked Oct 25 '12 19:10

Pi Horse


People also ask

How do you split an array in Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.


Video Answer


1 Answers

Try the partition method

@arr1, @arr2 = @level1.partition { |x| x[0] > 2.1 } 

The condition there may need to be adjusted, since that wasn't very well specified in the question, but that should provide a good starting point.

like image 110
qqx Avatar answered Sep 19 '22 18:09

qqx