Minimal refactoring of build.rb

Working towards a fix for #19857, I found some issues with dependency and requirement expansion in build.rb; it was being performed multiple times rather than storing the result.

There shouldn't be any user-visible changes here.