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.
class Version include Comparable attr_reader :major, :feature_group, :feature, :bugfix def initialize(version="") v = version.split(".") @major = v[0].to_i @feature_group = v[1].to_i @feature = v[2].to_i @bugfix = v[3].to_i end def <=>(other) return @major <=> other.major if ((@major <=> other.major) != 0) return @feature_group <=> other.feature_group if ((@feature_group <=> other.feature_group) != 0) return @feature <=> other.feature if ((@feature <=> other.feature) != 0) return @bugfix <=> other.bugfix end def self.sort self.sort!{|a,b| a <=> b} end def to_s @major.to_s + "." + @feature_group.to_s + "." + @feature.to_s + "." + @bugfix.to_s end end ## Example Usage: ## list = [] ## ["1.2.2.10","1.2.2.1","2.1.10.2","2.3.4.1"].each {|v| list.push(Version.new(v)) } ## list.sort.each{|v| pp v.to_s } ## ###"1.2.2.1" ###"1.2.2.10" ###"2.1.10.2" ###"2.3.4.1"
以上是关于Ruby类,用于简单的版本号自然顺序排序的主要内容,如果未能解决你的问题,请参考以下文章
Java自然排序键的Multimap,但是按照添加元素的顺序排序的集合