What is the difference between ~> and >= when specifying rubygem in Gemfile?

RubyRubygemsGemfile

Ruby Problem Overview


I often see the following notation(~>) in Gemfile.

gem "cucumber", "~>0.8.5"
gem "rspec", "~>1.3.0"

I know the sign (>=) is just greater or equal to, but what does the (~>) notation mean? Are they both same or has any significant difference?

Ruby Solutions


Solution 1 - Ruby

That's a pessimistic version constraint. RubyGems will increment the last digit in the version provided and use that until it reaches a maximum version. So ~>0.8.5 is semantically equivalent to:

gem "cucumber", ">=0.8.5", "<0.9.0"

The easy way to think about it is that you're okay with the last digit incrementing to some arbitrary value, but the ones preceding it in the string cannot be greater than what you provided. Thus for ~>0.8.5, any value is acceptable for the third digit (the 5) provided that it is greater than or equal to 5, but the leading 0.8 must be "0.8".

You might do this, for example, if you think that the 0.9 version is going to implement some breaking changes, but you know the entire 0.8.x release series is just bugfixes.

However, simply using ">=0.8.5" would indicate that any version later than (or equal to) 0.8.5 is acceptable. There is no upper bound.

Solution 2 - Ruby

@millisami You can even use to add dependencies with the gemspec using the pessimistic constraint like this:

gem.add_runtime_dependency "thor", "~> 0.18.1"

If you don't know much about gem development or are just getting into it, these are some good references:

  1. Tutorial that teaches you how to make your own RubyGem, the standard practices associated with it, and how to upload it so that others can install it.
  2. How to create a Gem from scratch with Bundler

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAutodidactView Question on Stackoverflow
Solution 1 - RubyeldarerathisView Answer on Stackoverflow
Solution 2 - RubystrangeloopsView Answer on Stackoverflow