Updating rubygems results in error

One of my gems (rails-haml 2.0) requires rubygems version >= 3.0. So I tried to update using

gem update --system

but the following error occurs:

ERROR:  While executing gem ... (Errno::EACCES)
    Permission denied @ rb_sysopen - /usr/local/lib/ruby/site_ruby/2.4.0/rubygems.rb

The following is my circleci config:

steps:
  - checkout
  - restore_cache:
      keys:
        - {{ checksum "Gemfile.lock" }}
  - run: gem update --system
  - run: gem install bundler -v '1.17.3'
  - run: bundle install
  - save_cache:
      key: {{ checksum "Gemfile.lock" }}
      paths:
        - vendor/bundle

You need to run this command with sudo. That should resolve the permissions error. By default builds do not run as root, so you don’t have permissions to write to system directories.