简体   繁体   English

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

[英]How to sort the array in ruby

I have a following array 我有以下数组

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

I need to sort this array in a way that I get following: 我需要按照以下方式对该数组进行排序:

["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"]

I tried to use the sort method arr.sort and arr.sort_by{|word| word.downcase} 我试图使用排序方法arr.sortarr.sort_by{|word| word.downcase} arr.sort_by{|word| word.downcase} But it is giving me output as arr.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"]

How can I do this? 我怎样才能做到这一点?

Try to use sort like this: 尝试使用像这样的排序:

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

If you need to sort by substring try something like this: 如果您需要按子字符串排序,请尝试以下操作:

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

EDIT: this should work: 编辑:这应该工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM