How To Change Ruby Version With Rbenv

Whether you’re working on multiple Ruby projects or just need to switch between different Ruby versions for compatibility reasons, rbenv is a popular and powerful tool that can help. In this blog post, we’ll discuss how to change your Ruby version using rbenv.

Step 1: Install Rbenv

If you haven’t already installed rbenv, you can do so via Homebrew on macOS or by cloning the repository on other systems. Here’s how:

macOS

$ brew install rbenv

Other Systems

$ git clone https://github.com/rbenv/rbenv.git ~/.rbenv
$ cd ~/.rbenv && src/configure && make -C src

Don’t forget to add rbenv to your shell’s path by appending this line to your ~/.bashrc, ~/.zshrc, or ~/.profile file:

export PATH="$HOME/.rbenv/bin:$PATH"

To enable shims and autocompletion, also add this line:

eval "$(rbenv init -)"

Step 2: Install Ruby Build

To simplify the process of installing new Ruby versions, we recommend installing the ruby-build plugin. You can do this with Homebrew on macOS or by cloning the repository on other systems.

macOS

$ brew install ruby-build

Other Systems

$ git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build

Step 3: Install the Desired Ruby Version

You can now install the Ruby version you want to switch to. First, list all available Ruby versions with this command:

$ rbenv install -l

Next, install the desired version (e.g., 2.7.0) with this command:

$ rbenv install 2.7.0

Step 4: Change the Ruby Version

With the desired Ruby version installed, you can now switch to it. rbenv allows you to set the Ruby version at the global, local, or shell levels. Here’s how:

Global

To set the Ruby version globally (i.e., for all projects on your system), run:

$ rbenv global 2.7.0

Local

To set the Ruby version locally (i.e., for a specific project), navigate to the project’s root directory and run:

$ rbenv local 2.7.0

Shell

To set the Ruby version for the current shell session only, run:

$ rbenv shell 2.7.0

Step 5: Verify the Ruby Version

To confirm that you’ve successfully switched to the desired Ruby version, run:

$ ruby -v

This should display the new version number, such as ruby 2.7.0.

Conclusion

You now know how to change the Ruby version using rbenv. This should make it much easier to work on different projects with varying Ruby version requirements. Happy coding!