简体   繁体   中英

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.sort_by{|word| word.downcase} But it is giving me output as

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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