Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting numeric strings in Ruby

Tags:

sorting

ruby

I've got an array of string version numbers which I'd like to sort but can't for the life of me get them to sort the way I want:

versions = [ "1.0.4", "1.0.6", "1.0.11", "1.1.9", "1.1.10", "1.0.16" ]

versions.sort_by {|v| [v.size]}
=> ["1.0.4", "1.0.6", "1.1.9", "1.0.11", "1.1.10", "1.0.16"]

Trying to achieve:

=> ["1.0.4", "1.0.6", "1.0.11", "1.0.16", "1.1.9", "1.1.10"]

It seems to have something to do with lexicographically but I'm having difficulty working out the sorting rule I need to apply.

Any help or a point in the right direction would be greatly appreciated.

like image 624
user2525123 Avatar asked Dec 12 '22 13:12

user2525123


1 Answers

versions = [ "1.0.4", "1.0.6", "1.0.11", "1.1.9", "1.1.10", "1.0.16" ]
sorted = versions.sort_by {|s| s.split('.').map(&:to_i) }
sorted # => ["1.0.4", "1.0.6", "1.0.11", "1.0.16", "1.1.9", "1.1.10"]

What this does is it splits strings into components and compares them numerically.

like image 191
Sergio Tulentsev Avatar answered Dec 25 '22 20:12

Sergio Tulentsev