我有以下数组:
test = [["E","188","12314","87235"],["B","1803","12314","87235"],["C","1508","12314","87235"]]
我想用内部数组中的第二个值(188,1803,1508)对整个数组进行排序。所以这就是我想要的。
test = [["E","188","12314","87235"],["C","1508","12314","87235"],["B","1803","12314","87235"]]
实现这一目标的最有效方法是什么?我需要写一个sort
来做吗?
答案 0 :(得分:3)
您可以使用sort_by
:
test.sort_by { |e| e[1].to_i }
答案 1 :(得分:1)
使用@Maxim的答案,但你也可以写:
test.sort { |e,f| e[1].to_i <=> f[1].to_i }
#=> [["E", "188", "12314", "87235"],
# ["C", "1508", "12314", "87235"],
# ["B", "1803", "12314", "87235"]]