Michael Moffat put the visitors ahead in the opening minute but Jim Jefferies's men were 4-1 up by the break.
Ryan Wallace levelled from the spot after 21 minutes. Alex Whittle, then put Dunfermline ahead and former Ayr midfielder Andy Geggan made it 3-1.
Josh Falkingham got number four and Wallace added his second of the day after 65 minutes.
Arbroath beat derby rivals Forfar Athletic 3-0 at Gayfield thanks to goals from Alan Cook in the first half and substitute Lee Sibanda and Lee Erwin in the second.
Forfar had former Arbroath favourite Gavin Swankie red-carded for dissent late on.
Brechin City and Stranraer played out an entertaining 1-1 draw at Glebe Park.
Alan Trouten scored for Brechin in the 27th-minute, getting up to convert the penalty after he was fouled inside the box, but Marc Corcoran equalised with a 54th-minute free kick.
Airdrieonians squeezed past East Fife 1-0 at New Bayview. Scott McBride, who looked dangerous all day, got the only goal with a deflected shot in the 12th minute.