development

루비에서 버전을 비교하는 방법?

big-blog 2020. 7. 25. 10:15
반응형

루비에서 버전을 비교하는 방법?


일부 버전 문자열을 비교하고 최신 버전을 얻는 코드를 작성하는 방법은 무엇입니까?

예를 들어 다음과 같은 문자열 '0.1', '0.2.1', '0.44'입니다.


Gem::Version.new('0.4.1') > Gem::Version.new('0.10.1')

비관적 버전 제약 조건 을 확인해야하는 경우 다음 과 같이 Gem :: Dependency를 사용할 수 있습니다 .

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

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')]

Versionomygem ( 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

너무 기울어지면 더 많은 함수 줄 바꿈을 수행하십시오.


Gem::Version 여기에가는 쉬운 방법입니다 :

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

보석을 사용하지 않고 손으로 직접 만들고 싶다면 조금보기 만해도 다음과 같은 것이 효과가 있습니다.

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

Essentially, you turn each version string in to an array of integers and then use the array comparison operator. You could break out the component steps to get something a little easier to follow if this is going in code somebody will need to maintain.


I had the same problem, I wanted a Gem-less version comparator, came up with this:

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

참고URL : https://stackoverflow.com/questions/2051229/how-to-compare-versions-in-ruby

반응형