Given the following array:
y = %w[A1 A2 B5 B12 A6 A8 B10 B3 B4 B8]
=> [\"A1\", \"A2\", \"B5\", \"B12\", \"A6\", \"A8\", \"B10\", \"B3\", \"B4\", \"B8\"]
A natural or lexicographic sort, not a standard character-value-based sort, would be needed. Something like these gems would be a starting point: https://github.com/dogweather/naturally, https://github.com/johnnyshields/naturalsort
Humans treat a string like "A2" as "A" followed by the number 2, and sort by using character-string sorting for the string part and numeric sorting for the numeric part. Standard sort()
uses character-value sorting treating the string as a sequence of characters regardless of what the characters are. So for sort()
"A10" and "A2" look like [ 'A', '1', '0' ] and [ 'A', '2' ], since '1' sorts before '2' and the following characters can't change that order "A10" thus sorts before "A2". For humans the same strings look like [ "A", 10 ] and [ "A", 2 ], 10 sorts after 2 so we get the opposite result. The strings can be manipulated to make the character-value-based sort()
produce the expected result by making the numeric portion fixed-width and zero-padding it on the left to avoid embedded spaces, making "A2" turn into "A02" which does sort before "A10" using standard sort()
.