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.

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