The Giants forged a 2-2 tie in the top of the eighth on Marco Scutaro's run-producing single.
A.J. Ellis was intentionally walked to get to Herrera, who made the Giants pay by lining a shot off the glove of second-baseman Scutaro, sending Ramirez home with the decisive run.
With the win, the Dodgers remained in contention with St. Louis for a National League wild card spot. They need two losses by the Cardinals and two more wins over the Giants in the season-ending series to reach the post-season.
Brandon League (2-1) earned the victory with a scoreless top of the ninth.
Jessica Simpson shares three-way kiss with friends in photo
Senate Democrats to pull all-nighter on climate change