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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With