Numerical string sorting in Ruby
Sakis Kasampallis
|
Jun 15, 2013
min read
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 :)