Compare library versions as "Gem::Version" instances, not as strings

Posted . Visible to the public. Repeats.

Sometimes we have to write code that behaves differently based on the version of a specific gem or the Ruby Version itself. The version comparison can often be seen with simple string comparison like so.

# ❌ Not recommended
if Rails.version > '6.1.7.8' || RUBY_VERSION > '3.1.4'
  raise Error, 'please check if the monkey patch below is still needed'
end

If you are lucky, the version comparison above works by coincidence. But chances are that you are not: For example, Rails version 6.1.10.8 would not raise an error in the code block above, because in an lexicographical comparison the statement '6.1.10.8' > '6.1.7.8' evaluates to false.

Just rely on Gem::Version#<=> Show archive.org snapshot in cases such as this, which is much more robust:

# ✔️ Recommended
if Gem::Version.new(Rails.version) > Gem::Version.new('6.1.7.8') || 
   Gem::Version.new(RUBY_VERSION) > Gem::Version.new('3.1.4')
  raise Error, 'please check if the monkey patch below is still needed'
end
Michael Leimstädtner
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Michael Leimstädtner to makandra dev (2024-09-05 11:39)