34

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?

4
  • 1
    can you show us your expected output? Commented Oct 25, 2012 at 19:33
  • @arr1 = { [3.1, 4], [3.0, 7]} @arr2 = { [2.1, 5], [2.0, 6], [1.9, 3]} Then I will reverse sort @arr2 which will give me the follwoing: @arr2 = { [1.9, 3] , [2.0, 6], [2.1, 5]} And then i would merge these 2 arrays Commented Oct 25, 2012 at 19:38
  • possible duplicate of Best way to split arrays into multiple small arrays in ruby Commented Jul 2, 2015 at 12:13
  • by values after you mean values greater than 2.1? Commented Sep 19, 2023 at 19:30

2 Answers 2

100

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You probably want to use x[0] <= 2.1
@texasbruce No, arr1 is supposed to contain the larger values, so the condition should not be reversed. In any case, since the question didn't do a very good job of specifying the exact condition I'm not too concerned about getting that exactly correct here.
Guys it says : undefined method `>' for ["3.1"]:Array
0

something like this?

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

arr1, arr2 = arr.inject([[], []]) do |f,a|
  a.first.to_f <= 2.1 ? f.last << a : f.first << a; f
end

arr = arr1 + arr2.reverse
# => [["3.1", 4], ["3.0", 7], ["1.9", 3], ["2.0", 6], ["2.1", 5]]

4 Comments

It says undefined method `<=' for ["3.0"]:Array
the code in my answer works well on 1.8.7(as on all other versions), here is the proof
I think the first element that is 3.1, 3.0, 2.1 and so on, in each row is considered as a string. How do I convert that to an integer. It is not able to compare because it a a string.
ok i managed to convert that to float and it works now. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.