You can install and switch between multiple Ruby versions on your machine using Homebrew and rbenv, which is crucial for managing project dependencies and avoiding conflicts.

Here’s how to set it up:

First, ensure you have Homebrew installed. If not, run this in your terminal:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Next, install rbenv and ruby-build (which rbenv uses to compile Ruby versions) via Homebrew:

brew update
brew install rbenv ruby-build

Now, you need to add rbenv to your shell’s startup file. This allows rbenv to intercept Ruby commands.

For Zsh (default on macOS Catalina and later):

echo 'eval "$(rbenv init zsh)"' >> ~/.zshrc
source ~/.zshrc

For Bash:

echo 'eval "$(rbenv init bash)"' >> ~/.bash_profile
source ~/.bash_profile

After restarting your terminal or sourcing your shell’s configuration file, you can list the Ruby versions rbenv knows how to install:

rbenv install --list

This will show a long list of available Ruby versions, including the latest stable releases and older versions.

To install a specific Ruby version, say 3.2.2, use:

rbenv install 3.2.2

This process can take a few minutes as ruby-build downloads the Ruby source code and compiles it on your machine.

Once installed, you can see which versions are available locally:

rbenv versions

This will list the installed versions, with an asterisk next to the one currently active.

To set a global Ruby version (the default for your entire system), use:

rbenv global 3.2.2

Now, if you run ruby -v, you should see ruby 3.2.2 ....

For project-specific Ruby versions, navigate to your project’s directory and use:

cd /path/to/your/project
rbenv local 3.1.4

This creates a .ruby-version file in your project’s root directory containing 3.1.4. When you cd into this directory, rbenv will automatically switch to that version.

You can verify the current version for your project by running ruby -v within the project directory. If you don’t have a .ruby-version file, rbenv falls back to the global version.

To uninstall a Ruby version managed by rbenv:

rbenv uninstall 3.2.2

This removes the compiled Ruby installation from your system.

The real power comes from rbenv’s shims. When you install a Ruby version, rbenv creates lightweight executable files (shims) in ~/.rbenv/shims. When you type ruby, gem, or bundle, rbenv intercepts these commands via the eval "$(rbenv init ...)" hook in your shell. It then looks at the active Ruby version (determined by the .ruby-version file in the current directory, or the global setting) and executes the appropriate command from that specific Ruby installation. This shims directory is automatically managed by rbenv and should not be edited manually.

The next step is often managing gem dependencies for each Ruby version, which bundler handles beautifully.

Want structured learning?

Take the full Homebrew course →