Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array of string by numbers

I want to sort an array like the following:

["10a","10b","9a","9b","8a","8b"]

When I call,

a = a.sort {|a,b| a <=> b}

it will sort like the following:

["10a","10b","8a","8b","9a","9b"]

The 10 is a string and is not handled as a number. When I first sort by integer and then by string, it will just do the same. Does anybody know how I can handle the 10 as a 10 without making it into an integer? That would mess up the letters a, b etc.

like image 948
Splinti Avatar asked Jul 16 '26 08:07

Splinti


1 Answers

When I first sort by integer and then by string, it will just do the same.

That would have been my first instinct, and it seems to work perfectly:

%w[10a 10b 9a 9b 8a 8b].sort_by {|el| [el.to_i, el] }
# => ['8a', '8b', '9a', '9b', '10a', '10b']
like image 61
Jörg W Mittag Avatar answered Jul 17 '26 22:07

Jörg W Mittag