100
votes

What's the meaning of ~> version requirement in gem specs?

hanna-0.1.12 depends on [haml (~> 2.2.8)]
4
+1 @SuckerForMayhem , "twiddle-wakka" is funnier. New link: guides.rubygems.org/patterns/#pessimistic-version-constraint -- which itself links to robots.thoughtbot.com/rubys-pessimistic-operatorThe Red Pea
@SuckerForMayhem Twiddle-wakka sounds like some kind of legendary beast like the chupacabra. This has been my contribution to the topic. You're welcome society.twiz
thx for updated links @TheRedPeaSuckerForMayhem

4 Answers

103
votes

The RubyGems manual calls this a pessimistic version constraint.

Assume you have specified an n-part version number, e.g. 1.3 (2-part) or 3.5.6.2 (4-part) as the constraint. Then, in order to fulfill the constraint, a version number must satisfy both of the following conditions

  1. The first n-1 parts of the version number must be identical to the first n-1 parts of the constraint (e.g. 1.x or 3.5.6.x match, but 0.x or 3.5.7.x don't) and

  2. The last part of the version number must be greater than or equal to the last part of the constraint (e.g. 1.9999 and 3.5.6.2 match, but 1.2 or 3.5.6.1 don't).

In other words

~> x1.x2.x3. … .xn-2.xn-1.xn

matches

x1.x2.x3. … .xn-2.xn-1.y, y >= xn

The reason this is called a "pessimistic" constraint, and also the use case for it, is that when you just say > x.y.z, you are being optimistic: you assume that from here on out, until all eternity, the API will never ever change. This is of course a pretty bold assumption. However, most projects have rules about when they are allowed to break backwards compatibility, and how they have to change their version number when they do break backwards compatibility. You can encode those version numbering rules using a pessimistic constraint, and thus you can be sure that your code will always continue to work (assuming that the author of the other project actually adheres to his own rules, which unfortunately isn't always the case).

22
votes

In other words, you can use this symbol to keep your gem updated with all the minor updates and avoid making a major update that can break your app.

For example "~> 1.2" will update your gem to 1.3 (if such a version is released) but it won’t update it to 2.0

14
votes

I think bundler docs best sum this up:

The specifier ~> has a special meaning, best shown by example. ~> 2.0.3 is identical to >= 2.0.3 and < 2.1. ~> 2.1 is identical to >= 2.1 and < 3.0. ~> 2.2.beta will match prerelease versions like 2.2.beta.12.

-1
votes

It matches any version that has the same major / minor part. This means in this case that haml ~> 2.2.8 will match any 2.2.x version.

This can be used to make sure that an API breaking change in a new gem, doesn't result in depending on that newly but changed gem that would break hanna in this case.