Sorting numeric strings in Ruby

I have an array of string version numbers that I would like to sort, but I canโ€™t force me to sort them for the rest of my life 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"] 

Attempt to achieve:

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

Something seems to be related to lexicography, but it's hard for me to develop a sorting rule that I need to apply.

Any help or point in the right direction is welcome.

+4
source share
1 answer
 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 means is that it breaks the strings into components and compares them numerically.

+13
source

Source: https://habr.com/ru/post/1488337/


All Articles