Ruby & gt; Sort images in the directory with several conditions

advertisements

I need to sort the images present inside some directory with the following order:

00a.jpg
00b.jpg
00c.jpg
...
00x.jpg
00y.jpg
00z.jpg
0aa.jpg
0bb.jpg
0cc.jpg
...
0xx.jpg
0yy.jpg
0zz.jpg
001.jpg
002.jpg
003.jpg
...
097.jpg
098.jpg
099.jpg
100.jpg
101.jpg
102.jpg

But I am not getting any logic to put inside my sort_by? Can anyone has any idea what logic would be best suited for sorting all images in the above mentioned order..

I am expecting something like this :

Dir.entries('.').sort_by { |x| ?? }

Thanks, Dean


Your requested sort order is not apparent, so I'm going to assume that you want all the images which contain a letter to be before those with numbers only.

For this logic, you can return an array from sort_by, which be evaluated in order - firs item first, second one if the first is tied, etc.

In this example this would be something like:

jpgs.sort_by { |j| [j[/.*[a-z].*\.jpg/] ? 0 : 1, j] }

The first item in the array returned answers the question of whether the image name contains a letter before the extension, and if it does returns a smaller number than if it doesn't. This assures us that images with letters in their names will be before images with only numbers in their names.

Will result in this order:

[
    "00a.jpg",
    "00b.jpg",
    "00c.jpg",
    "00x.jpg",
    "00y.jpg",
    "00z.jpg",
    "0aa.jpg",
    "0bb.jpg",
    "0cc.jpg",
    "0xx.jpg",
    "0yy.jpg",
    "0zz.jpg",
    ...,
    "001.jpg",
    "002.jpg",
    "003.jpg",
    "097.jpg",
    "098.jpg",
    "099.jpg",
    "100.jpg",
    "101.jpg",
    "102.jpg"
]