Ruby类,用于简单的版本号自然顺序排序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ruby类,用于简单的版本号自然顺序排序相关的知识,希望对你有一定的参考价值。

Probably not the most elegant solution, but it works. Needed this for a capistrano deploy task which shows the most recent tagged releases in my repository. Very bare bones, and needs tweaking if your versions are not in X.X.X.X format.
  1. class Version
  2. include Comparable
  3.  
  4. attr_reader :major, :feature_group, :feature, :bugfix
  5.  
  6. def initialize(version="")
  7. v = version.split(".")
  8. @major = v[0].to_i
  9. @feature_group = v[1].to_i
  10. @feature = v[2].to_i
  11. @bugfix = v[3].to_i
  12. end
  13.  
  14. def <=>(other)
  15. return @major <=> other.major if ((@major <=> other.major) != 0)
  16. return @feature_group <=> other.feature_group if ((@feature_group <=> other.feature_group) != 0)
  17. return @feature <=> other.feature if ((@feature <=> other.feature) != 0)
  18. return @bugfix <=> other.bugfix
  19. end
  20.  
  21. def self.sort
  22. self.sort!{|a,b| a <=> b}
  23. end
  24.  
  25. def to_s
  26. @major.to_s + "." + @feature_group.to_s + "." + @feature.to_s + "." + @bugfix.to_s
  27. end
  28. end
  29.  
  30. ## Example Usage:
  31. ## list = []
  32. ## ["1.2.2.10","1.2.2.1","2.1.10.2","2.3.4.1"].each {|v| list.push(Version.new(v)) }
  33. ## list.sort.each{|v| pp v.to_s }
  34. ##
  35. ###"1.2.2.1"
  36. ###"1.2.2.10"
  37. ###"2.1.10.2"
  38. ###"2.3.4.1"

以上是关于Ruby类,用于简单的版本号自然顺序排序的主要内容,如果未能解决你的问题,请参考以下文章

Java自然排序键的Multimap,但是按照添加元素的顺序排序的集合

Java 8 新特性:Comparator.naturalOrder | 自然排序

在对象更改值时维护 TreeSet 排序

自然或人为排序顺序

gitlab 9.0对ruby的版本有要求吗

Ruby 维护 Hash 插入顺序