John Mayberry ignited Philadelphia's four-run fifth with a one-out solo homer, tying the score 1-1.
That brought up Ruiz, who sliced the first pitch he saw into the right-field corner to drive in all three runners.
Hamels (8-13) earned the victory, allowing four runs (three earned) on eight hits through six innings, walking three and striking out five.
B.J. Rosenberg and Jacob Diekman held the Nats scoreless over 1 1/3 innings and Jonathan Papelbon notched his 27th save despite allowing a hit and a walk in the ninth as Philadelphia evened the three-game series.
Gonzalez (10-7) coughed up four runs on nine hits over six innings for Washington, which had used the winning streak to pull within 5 1/2 games of Cincinnati for the second National League wild-card spot.