Help more people learn by sharing 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:

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

Ruby sort by value

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

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.

Ruby-doc: http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-sort_by

2 comments
tvinky says 10 months ago

Hi!
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 10 months ago

    Hey,
    You are right :) I think the \ got lost when moving the blog data to a new server.

Comments are closed