Ayr ended their horror home run with a late goal from teenager Craig Pettigrew as they stretched their winning run to three games.
The youngster, who was on as a first-half substitute playing out of position in midfield, picked up the ball 30 yards from goal before going on a mazy run and scoring off the underside of the bar.
It brought to a climax a pulsating game at Somerset Park with chances aplenty for both sides.
And Raith were left to curse the missed opportunities they wasted during the game.
The first half had belonged to the visitors and powerful striker Armand One ran the show and had two efforts cleared off the line.
Meanwhile, Ayr goalkeeper Mark McGeown had to make three great saves before the break to keep his side on level terms.
But Ayr rode the storm and began to create chances of their own with Chris Robertson smashing a header off the bar and Jerome Vareille shooting inches wide of the post.
The second half saw fewer chances but was still high on excitement and Ayr felt they should have had a penalty when Raith stopper Mark Campbell handballed in the box before Ryan Caddis shot just wide.
But the home side were gathering the momentum and they eventually got their reward in the closing stages when Pettigrew popped with a brilliant winner to raise the roof and it was a fitting end to a cracking match.