Numerical string sorting in Ruby

Sakis Kasampallis | Jun 15, 2013 min read
The problem: You have an unsorted array of strings (product codes, area codes, etc.) containing both letters and numbers (for example 'A28', 'A3', 'A1', etc.) and you want to sort them numerically (that is, 'A1', 'A2', ..., 'An'). Ruby offers a sort method, so let's see what it does...

Nope, that's not what I want. But no worries, enumerable is here to help me. Enumerable is a great mixin inspired by functional programming. Functional programming relies heavily on data transformations: The input is a data structure, we transform the data of the structure by applying one or more functions, and the output is a new data structure. In this particular example the input is an unsorted array of strings, I want to apply a function that will change their order, and the output will be a new array with the strings sorted numerically.

What is the data transformation in this case? A string is a data structure that can be treated as an array in most programming languages, and ruby is not an exception. Therefore the problem can be solved by using as a sorting key the numeric part of a string and treating that key as a number.

And we are done :)