Afghanistan was on track to chase down a target of 312 when the 39-year-old Gayle, with his occasional offspin, trapped 18-year-old batsman Ikram Ali Khil in front of his stumps and took out Afghanistan's key man for 86.
It sparked a mini-collapse by the Afghans, who lost two more wickets in the next 13 balls to slip from 189-2 to 201-5. They were dismissed for 288 on the last ball of the match, their highest total at a World Cup but still not enough to avoid returning home with a sweep of nine losses.
Gayle — making his record-tying 295th ODI appearance for the Windies and last in World Cups — had bowling figures of 1-28 off his six overs to make up for only getting 7 off 18 balls with the bat. Gayle had needed 18 runs to top Brian Lara (10,348) as West Indies' leading scorer in ODIs.
Next-to-last West Indies ended the World Cup with two victories — from their first and last games — and moved level on five points on South Africa, which still has a match to play against Australia.
The Windies won the toss and made 311-6, with Evin Lewis (58) and Shai Hope (77) scoring half-centuries before Nicholas Pooran (58 off 43) and Jason Holder (45 off 34, including four sixes) helped the team rack up a match-defining 111 runs off the last 10 overs.