Ruby class for easy version number natural order sorting


/ Published in: Ruby
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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"

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.