如何比较 Ruby 中的版本?

如何编写一段代码来比较一些版本字符串并获得最新版本?

例如字符串: '0.1', '0.2.1', '0.44'

28613 次浏览

你可使用 Versionomy宝石(可在 Github下载) :

require 'versionomy'


v1 = Versionomy.parse('0.1')
v2 = Versionomy.parse('0.2.1')
v3 = Versionomy.parse('0.44')


v1 < v2  # => true
v2 < v3  # => true


v1 > v2  # => false
v2 > v3  # => false

我会的

a1 = v1.split('.').map{|s|s.to_i}
a2 = v2.split('.').map{|s|s.to_i}

然后你就可以

a1 <=> a2

(可能还有其他所有“通常”的比较)。

如果你想做 <或者 >测试,你可以做例如。

(a1 <=> a2) < 0

或者做一些功能包装,如果你愿意的话。

如果你想不使用任何宝石手工完成,像下面这样的东西应该可以工作,虽然它看起来有点怪异。

versions = [ '0.10', '0.2.1', '0.4' ]
versions.map{ |v| (v.split '.').collect(&:to_i) }.max.join '.'

实际上,您将每个版本字符串转换为一个整数数组,然后使用 数组比较运算符数组比较运算符。如果代码中有人需要维护,那么您可以分解组件步骤来获得一些更容易遵循的内容。

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')]
Gem::Version.new('0.4.1') > Gem::Version.new('0.10.1')

在这里,Gem::Version是一种简单的方法:

%w<0.1 0.2.1 0.44>.map {|v| Gem::Version.new v}.max.to_s
=> "0.44"

如果你需要检查 悲观版本约束,你可以这样使用 宝石: : 依赖:

Gem::Dependency.new('', '~> 1.4.5').match?('', '1.4.6beta4')

我也有同样的问题,我想要一个无 Gem 版本的比较器,想出了这个:

def compare_versions(versionString1,versionString2)
v1 = versionString1.split('.').collect(&:to_i)
v2 = versionString2.split('.').collect(&:to_i)
#pad with zeroes so they're the same length
while v1.length < v2.length
v1.push(0)
end
while v2.length < v1.length
v2.push(0)
end
for pair in v1.zip(v2)
diff = pair[0] - pair[1]
return diff if diff != 0
end
return 0
end