How to compare versions in Ruby?

前端 未结 8 2021
耶瑟儿~
耶瑟儿~ 2020-12-12 19:47

How to write a piece of code to compare some versions strings and get the newest?

For example strings like: \'0.1\', \'0.2.1\', \'0.44\'.

8条回答
  •  隐瞒了意图╮
    2020-12-12 20:33

    class Version < Array
      def initialize s
        super(s.split('.').map { |e| e.to_i })
      end
      def < x
        (self <=> x) < 0
      end
      def > x
        (self <=> x) > 0
      end
      def == x
        (self <=> x) == 0
      end
    end
    p [Version.new('1.2') < Version.new('1.2.1')]
    p [Version.new('1.2') < Version.new('1.10.1')]
    

提交回复
热议问题