The issue is due to macOS’s system Ruby being protected, which prevents installing gems globally without sudo. To fix this, use a Ruby version manager like rbenv or RVM to install and manage Ruby versions locally, avoiding conflicts with the system Ruby.

Here’s how to resolve this issue and properly manage your Ruby environment on macOS:

1. Install a Ruby Version Manager

Using a Ruby version manager allows you to manage multiple Ruby versions and avoid conflicts with the system Ruby.

Two popular options are:
rbenv
RVM

Add rbenv to your shell:
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(rbenv init - zsh)"' >> ~/.zshrc
source ~/.zshrc

Verify the installation:
rbenv -v

2. List available Ruby versions:

rbenv install -l

Install Ruby 3.1:
rbenv install 3.1.0

Set Ruby 3.1 as the global version:
rbenv global 3.1.0

Verify Ruby version:
ruby -v

3. Install Rails

gem install rails

4. Verify Rails Installation

rails -v

5. Alternative: Use RVM

Install RVM:
\curl -sSL https://get.rvm.io | bash -s stable

Install Ruby 3.1 and set it as default:
rvm install 3.1
rvm use 3.1 --default

Install Rails:
gem install rails

6. Remove Conflicts with System Ruby

Use the rbenv or rvm paths exclusively.
Avoid sudo for installing gems unless absolutely necessary.

Support On Demand!

Ruby on Rails

Related Q&A