1

I have the following array:

test = [["E","188","12314","87235"],["B","1803","12314","87235"],["C","1508","12314","87235"]]

I want to sort the whole array by the second value in the inner arrays (188,1803,1508). So this is what I want to have.

test = [["E","188","12314","87235"],["C","1508","12314","87235"],["B","1803","12314","87235"]]

What would be the most efficient way to achieve this? Do I need to write a sort to do it?

5
  • The logic is not clear. If you sort them, the order should be "1508", "1803", "188". Commented Apr 15, 2016 at 15:43
  • What do you mean by the order should be "1508", "1803", "188"? I want them to be in ascending order. Commented Apr 15, 2016 at 15:54
  • Yes. ascending order. Just try it. ["188", "1803", "1508"].sort # => ["1508", "1803", "188"]. Commented Apr 15, 2016 at 15:55
  • That's because the elements are strings, not integers. Commented Apr 15, 2016 at 16:03
  • 1
    Jack, @sawa is making the point that if you want the arrays sorted by the second elements after they are converted to integers, you've got to say that. You may think it's obvious, but it's not. Programming is all about precision, with your description of what you want to do or have done, as well as the code itself. Commented Apr 15, 2016 at 18:46

2 Answers 2

3

You can achieve it with sort_by:

test.sort_by { |e| e[1].to_i }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This helped a lot.
1

Go with @Maxim's answer, but you could also write:

test.sort { |e,f| e[1].to_i <=> f[1].to_i }
  #=> [["E",  "188", "12314", "87235"],
  #    ["C", "1508", "12314", "87235"],
  #    ["B", "1803", "12314", "87235"]] 

Comments

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.