Help more people learn by sharing this post!

Tag Archives for " numeric value "

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