4

我有一个字符串版本号数组,我想对其进行排序,但我一生都无法让它们按照我想要的方式排序:

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"]

试图达到:

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

它似乎与字典顺序有关,但我很难制定出我需要应用的排序规则。

任何帮助或正确方向的观点将不胜感激。

4

1 回答 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"]

它的作用是将字符串拆分为组件并进行数字比较。

于 2013-06-26T17:27:31.360 回答