在内部数组中按一定值对数组数组进行排序

时间:2016-04-15 15:38:39

标签: ruby

我有以下数组:

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来做吗?

2 个答案:

答案 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"]]