如何在ruby中对数组进行排序

时间:2014-05-03 07:15:39

标签: ruby ruby-1.9.3 ruby-1.9

我有一个以下数组

arr = ["2014-05-02T19-49-55_1280x720_vga2usb.mp4", "2014-05-02T19-49-55_544x288_left_cam.mp4", "2014-05-02T19-49-55_544x288_right_cam.mp4", "2014-05-02T19-49-55_1632x288.mp4"]

我需要按照以下方式对此数组进行排序:

["2014-05-02T19-49-55_1632x288.mp4", "2014-05-02T19-49-55_544x288_left_cam.mp4", "2014-05-02T19-49-55_544x288_right_cam.mp4", "2014-05-02T19-49-55_1280x720_vga2usb.mp4"]

我尝试使用排序方法arr.sortarr.sort_by{|word| word.downcase} 但它正在给我输出

["2014-05-02T19-49-55_1280x720_vga2usb.mp4", "2014-05-02T19-49-55_1632x288.mp4", "2014-05-02T19-49-55_544x288_left_cam.mp4", "2014-05-02T19-49-55_544x288_right_cam.mp4"]

我该怎么做?

1 个答案:

答案 0 :(得分:0)

尝试使用这样的排序:

arr.sort { |x,y| y <=> x }

如果你需要按子串排序尝试这样的事情:

arr.sort { |x,y| y[m,n] <=> x[m,n]}

编辑:这应该有效:

arr.sort do |x,y| 
    regex = /x[[:digit:]]+(.+?)$/
    regex.match(x)[1] <=> regex.match(y)[1]
end