Question

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} 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?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top