I was trying to install this on an old MacBook Air (OS Monterey) . Lots of similar issues. Found a lot of posts here and on StackOverflow. End result, this worked. Posting here as currently valid.
Navigate to where Ruby is installed. Check the log file mentioned in the error message, that should be a clue.
Run this command -
$ ??? % cd /Applications/XCode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/include/ruby-2.6.0
% cd ruby
%ls ( Check if config.h is present in this directory) . If you see it, proceed to -
% sudo gem install -n/usr/local/bin cocoapods -v 1.8.4