diff --git a/Library/Homebrew/extend/rbconfig_extension.rb b/Library/Homebrew/extend/rbconfig_extension.rb
new file mode 100644
index 0000000000000000000000000000000000000000..e26042eb66e08f5dbd89700d58d2466dfb519ea3
--- /dev/null
+++ b/Library/Homebrew/extend/rbconfig_extension.rb
@@ -0,0 +1,17 @@
+# typed: false
+# frozen_string_literal: true
+
+macos_version = ENV["HOMEBREW_MACOS_VERSION"][0..4]
+macos_sdk = "MacOSX#{macos_version}.sdk"
+
+# Ruby hardcodes what might end up being an incorrect SDK path in some of the
+# variables that get used in mkmf.rb.
+# This patches them up to use the correct SDK.
+RbConfig::CONFIG.each do |k, v|
+  next unless v.include?("MacOSX.sdk")
+
+  new_value = v.gsub("MacOSX.sdk", macos_sdk)
+  next unless File.exist?(new_value)
+
+  RbConfig::CONFIG[k] = new_value
+end
diff --git a/Library/Homebrew/utils/gems.rb b/Library/Homebrew/utils/gems.rb
index a75f0b8561e06558c9393d3a581a3e9f9f9158a7..3e5c9105500d12ec2ccf1e2720f3900509b08b18 100644
--- a/Library/Homebrew/utils/gems.rb
+++ b/Library/Homebrew/utils/gems.rb
@@ -109,6 +109,15 @@ module Homebrew
     install_bundler!
 
     ENV["BUNDLE_GEMFILE"] = File.join(ENV.fetch("HOMEBREW_LIBRARY"), "Homebrew", "Gemfile")
+
+    # We can't use OS.mac? because not enough has
+    # been required yet this early in the boot process
+    if ENV["HOMEBREW_SYSTEM"] == "Macintosh"
+      # This patches up some paths used by mkmf.rb
+      extend_path = File.join(ENV.fetch("HOMEBREW_LIBRARY"), "Homebrew", "extend")
+      ENV["RUBYOPT"] = "-r#{extend_path}/rbconfig_extension"
+    end
+
     @bundle_installed ||= begin
       bundle = File.join(find_in_path("bundle"), "bundle")
       bundle_check_output = `#{bundle} check 2>&1`
@@ -126,6 +135,8 @@ module Homebrew
       end
     end
 
+    ENV["RUBYOPT"] = ""
+
     setup_gem_environment!
   end
 end