The Pirates led 3-1 when the Phillies came up with four runs in the top of the sixth inning, highlighted by Ruiz's two-run single.
Kevin Frandsen drove in two runs for Philadelphia, which took two games of three games to win a series in Pittsburgh for the first time since April 2008.
Phillies starter Cole Hamels (3-11) went seven innings, striking out eight and allowing two runs on five hits with no walks. Justin De Fratis gave up two runs on three hits in one inning of relief and Jonathan Papelbon nailed down the save with a scoreless ninth.
Gerrit Cole (4-1) gave up three runs on eight hits in 5 1/3 innings and Andrew McCutchen drove in two runs for the Pirates.