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:
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
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
gem install rails
rails -v
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
Use the rbenv or rvm paths exclusively.
Avoid sudo for installing gems unless absolutely necessary.