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.
Notable deaths of 2014 [PHOTOS]