4

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.

1
  • Break it apart into individual numbers and sort by each. Or use multiplication and do 1st * 1000, 2nd * 100, etc. and add 'em up. Commented Jun 26, 2013 at 17:27

1 Answer 1

13
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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Stefan: thanks for fixing the output. Messed that up a little bit while editing :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.