Lazio dominated for long spells in the first half and should have taken the lead early on but Luis Alberto fired wide from a good position.
Napoli improved after the break, with Lorenzo Insigne arrowing a fierce strike into the net to give his side the lead in the 62nd minute.
Insigne thought he had added a quickfire second goal only to see his close-range finish ruled out for offside after a VAR review. That setback looked like it would prove costly when Pedro lashed home the equaliser two minutes from time.
The drama was not finished there, however, as a fine finish from Ruiz four minutes into stoppage time snatched victory for Napoli, moving them top above AC Milan, who are level on points but have a worse goal difference. Lazio dropped to seventh.