The Giants had taken a 2-to-1 lead when Guillermo Rodriguez poked an R-B-I single in the top of the eighth. But Ryan Theriot and Derrek Lee hit two-out singles before Ramirez sent the Cubs to the 16th victory in their last 20 games.
Giants outfielder Barry Bonds was a late scratch as he fights an 0-for-20 slump. Bonds hasn't homered since July third, leaving him four behind Hank Aaron's career record of 755.
Koyie Hill homered for the Cubs before Pedro Feliz went deep for the Giants.
Rich Hill is 6-and-6 after winning for the first time in more than a month. Hill allowed four hits in eight innings before Bobby Howry tossed the ninth for his sixth save.
Kevin Correia dropped to 1-and-5.