Errno::EACCES: Permission denied @ dir_s_mkdir が出たので対処した

環境

自分の状況など

これまではrbenvでRubyを扱っていたが、2018年3月21日からanyenvで入れたrbenvを使う形式に変えた。

その際に、rbenvのディレクトリをsudo rm -rf .rbenv という形で削除した。

そして今日(2018年3月22日)、rails newしたらこのようなエラーが出た。(エラー部分だけ記述)

Fetching bindex 0.5.0
Installing bindex 0.5.0 with native extensions
Errno::EACCES: Permission denied @ dir_s_mkdir -
/usr/local/lib/ruby/gems/2.5.0/extensions/x86_64-darwin-17/2.5.0/bindex-0.5.0
An error occurred while installing bindex (0.5.0), and Bundler
cannot continue.
Make sure that `gem install bindex -v '0.5.0'` succeeds before bundling.

In Gemfile:
  web-console was resolved to 3.5.1, which depends on
    bindex
         run  bundle exec spring binstub --all
bundler: command not found: spring
Install missing gem executables with `bundle install`

最初は指示通り、gem install bindex -v '0.5.0'としたが、直らなかったので色々調べた。

その結果わかったことを以下に記す。

手順

ディレクトリやファイルの所有者が root になっていたので、次のコマンドで username にしてやる。

chown -R username /usr/local/lib/ruby/gems/2.5.0/extensions

-R オプションをつけると、ディレクトリとその中身を再帰的に変更してくれる。

参考にした記事など

[macOS Sierra] nokogiri インストール中のエラー "Permission denied @ dir_s_mkdir" の 1解決手法 - Qiita