How to fix undefined local variable or method `d' for Gem::Specification:Class

If you’re seeing a weird invalid gemspec error that looks like this:

Invalid gemspec in [~/.gem/ruby/2.7.4/specifications/jekyll-4.2.1.gemspec]: 
undefined local variable or method `d' for Gem::Specification:Class

or this:

Invalid gemspec in [~/.gem/ruby/2.7.4/specifications/rails-7.0.0.gemspec]: 
undefined local variable or method `d' for Gem::Specification:Class

or this:

Invalid gemspec in [~/.gem/ruby/3.0.3/specifications/bundler-2.2.32.gemspec]: 
undefined local variable or method `d' for Gem::Specification:Class
ERROR:  While executing gem ... (NoMethodError)
    undefined method `name' for nil:NilClass

Invalid gemspec in [~/.gem/ruby/3.0.3/specifications/bundler-2.2.32.gemspec]: 
undefined local variable or method `d' for Gem::Specification:Class
ERROR:  While executing gem ... (NoMethodError)
    undefined method `version' for nil:NilClass

Invalid gemspec in [~/.gem/ruby/3.0.3/specifications/bundler-2.2.32.gemspec]: 
undefined local variable or method `d' for Gem::Specification:Class
ERROR:  While executing gem ... (NoMethodError)
    undefined method `platform' for nil:NilClass

it’s a known bug in Rubygems that was fixed on December 23, 2021.

Before you update to the latest version of Rubygems, you’ll need to fix the issue first. You have 2 options:

Delete and reinstall the affected gemspec

Delete the affected gemspec, as listed in the error message. For example:

rm ~/.gem/ruby/2.7.4/specifications/rails-7.0.0.gemspec

Update Rubygems:

gem update --system

Reinstall the gem:

gem install rails

Fix the affected gemspec manually

Open the affected gemspec, for example:

open ~/.gem/ruby/2.7.4/specifications/rails-7.0.0.gemspec

Remove any stray characters at the end of the file after the last end, and save the file.

Update Rubygems:

gem update --system