Posted By

bananastalktome on 07/31/09


Tagged

sort number ruby version order Natural


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

webstic


Ruby class for easy version number natural order sorting


 / Published in: 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"

Report this snippet  

You need to login to post a comment.