Share this post!

Alphanumeric sorting

Time for a bit more sorting. Today our task is to sort an array of file names based on the numeric value. This what the array looks like:

["20.mp3", "11.mp3", "3.mp3", "2.mp3", "21.mp3", "10.mp3", "1.mp3"]

If you try a simple sort it won’t come out as you expect…

["1.mp3", "10.mp3", "11.mp3", "2.mp3", "20.mp3", "21.mp3", "3.mp3"]

Ruby sort by value

This is not what we want, so we will have to reach for sort_by again:

files.sort_by{ |m| m.scan(/\d+/)[0].to_i }
=> ["1.mp3", "2.mp3", "3.mp3", "10.mp3", "11.mp3", "20.mp3", "21.mp3"]

And this time we get what we want. What we are doing here is taking each element of the array and using a regexp to scan for decimal numbers (\d+ or also [0-9]+) since we get an string back we need to convert it to a number with to_i. Hope you find it useful.


tvinky says a couple of years ago

Shouldn’t we write \d+ in this #scan method?

When I tried in IRB simple example: "21.mp3".scan(/d+/) I got empty array with Ruby 2.1.4. As far as I remember special RegEx symbols were needing in backslash \ before them.
Trying out with "21.mp3".scan(/\d+/) everything was working as supposed.

    Jesus Castello says a couple of years ago

    You are right 🙂 I think the \ got lost when moving the blog data to a new server.

Comments are closed