Reputation: 19
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?
Upvotes: 1
Views: 66
Reputation: 110675
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"]]
Upvotes: 1
Reputation: 3043
You can achieve it with sort_by
:
test.sort_by { |e| e[1].to_i }
Upvotes: 3