When compare two version strings, to_f
does not work well:
当比较两个版本字符串时,to_f不能很好地工作:
> "1.5.8".to_f > "1.5.7".to_f
=> false
string comparison is better, but not always correct:
字符串比较更好,但并不总是正确的:
> "1.5.8" > "1.5.7"
=> true
> "1.5.8" > "1.5.9"
=> false
> "1.5.8" > "1.5.10" # oops!
=> true
How to compare version strings properly?
如何正确地比较版本字符串?
3 个解决方案
#1
4
An idea: create a Object#compare_by
method that behaves like compare
(aka the spaceship operator Object#<=>) but takes a custom block:
一个想法:创建一个对象#compare_by方法,它的行为类似于compare(也就是太空船操作员对象#<=>),但它采用了一个自定义块:
class Object
def compare_by(other)
yield(self) <=> yield(other)
end
end
>> "1.5.2".compare_by("1.5.7") { |s| s.split(".").map(&:to_i) }
#=> -1
You can also take a more specific approach still based on the compare
method:
您还可以基于比较方法采取更具体的方法:
class String
def compare_by_fields(other, fieldsep = ".")
cmp = proc { |s| s.split(fieldsep).map(&:to_i) }
cmp.call(self) <=> cmp.call(other)
end
end
>> "1.5.8".compare_by_fields("1.5.8")
#=> 0
#2
4
Personally I'd probably just use the Versionomy gem, no need to reinvent this specific wheel IMHO.
就我个人而言,我可能只是使用了Versionomy gem,没有必要重新发明这个特定的*IMHO。
Example:
例子:
require 'versionomy'
v1 = Versionomy.parse("1.5.8")
v2 = Versionomy.parse("1.5.10")
v2 > v1
#=> true
#3
0
First start off by splitting the different parts of the versions:
首先,将版本的不同部分分开:
v1 = "1.5.8"
v2 = "1.5.7"
v1_arr = v1.split(".")
=> ["1", "5", "8"]
v2_arr = v2.split(".")
=> ["1", "5", "7"]
v1_arr.size.times do |index|
if v1_arr[index] != v2_arr[index]
# compare the values at the given index. Don't forget to use to_i!
break
end
end
#1
4
An idea: create a Object#compare_by
method that behaves like compare
(aka the spaceship operator Object#<=>) but takes a custom block:
一个想法:创建一个对象#compare_by方法,它的行为类似于compare(也就是太空船操作员对象#<=>),但它采用了一个自定义块:
class Object
def compare_by(other)
yield(self) <=> yield(other)
end
end
>> "1.5.2".compare_by("1.5.7") { |s| s.split(".").map(&:to_i) }
#=> -1
You can also take a more specific approach still based on the compare
method:
您还可以基于比较方法采取更具体的方法:
class String
def compare_by_fields(other, fieldsep = ".")
cmp = proc { |s| s.split(fieldsep).map(&:to_i) }
cmp.call(self) <=> cmp.call(other)
end
end
>> "1.5.8".compare_by_fields("1.5.8")
#=> 0
#2
4
Personally I'd probably just use the Versionomy gem, no need to reinvent this specific wheel IMHO.
就我个人而言,我可能只是使用了Versionomy gem,没有必要重新发明这个特定的*IMHO。
Example:
例子:
require 'versionomy'
v1 = Versionomy.parse("1.5.8")
v2 = Versionomy.parse("1.5.10")
v2 > v1
#=> true
#3
0
First start off by splitting the different parts of the versions:
首先,将版本的不同部分分开:
v1 = "1.5.8"
v2 = "1.5.7"
v1_arr = v1.split(".")
=> ["1", "5", "8"]
v2_arr = v2.split(".")
=> ["1", "5", "7"]
v1_arr.size.times do |index|
if v1_arr[index] != v2_arr[index]
# compare the values at the given index. Don't forget to use to_i!
break
end
end