Falling white dice

Read the .ruby-version into your Gemfile

Previously I recommended using a loose version ruby version constraint in your Gemfile. This is still a valuable technique, but here’s another useful variation that’s works well for most of us, most of the time.

Hat tip to Emma for the this one-liner.

Ruby version managers (such as chruby) ensure an application uses a specific version of Ruby by looking for a .ruby-version file in the root directory of each app.

The file specifies the required version of Ruby for the application and the manager automatically switches the environment to use the specified version.

The version can also be specified in your Gemfile using bundler, which is more often used to define the version of Ruby to use in a deployed application.

Instead of…

…specifying your exact ruby version in two places and potentially generating conflicts:

# Gemfile
ruby "2.7.2"
# .ruby-version
3.0.0

This results in an error, as bundler checks the current version of Ruby specified in the Gemfile.

Your Ruby version is 3.0.0, but your Gemfile specified 2.7.2

Use

…the fact that the Gemfile is simply another Ruby file:

# Gemfile
ruby File.read(".ruby-version").strip
# .ruby-version
3.0.0

Why?

This means that when you upgrade Ruby you only need to update in one place: the .ruby-version file.

Most of us, most of the time, are happy to specify a version of Ruby for all environments and this is a cool micro-improvement that reminds us that the Gemfile is just another ruby script!

Why not?

There are still services where the availability of new Ruby versions are delayed so the prevous loose ruby version technique might be a better fit for your project.


last updated on 11 Jan 2021 by @andycroll

photo by
Riho Kroll

Don’t miss my next post, sign up to the One Ruby Thing email and get my next post in your inbox.

Don’t miss my next post, sign up to the One Ruby Thing email and get my next post in your inbox.