El Salvador, which was winless in six matches in its two previous appearances at the Beach World Cup before arriving in Italy, finished second in Group B with six points, three behind Portugal, and will face the host country in the knockout round on Thursday.
Despite Ruiz being denied on a penalty in the fifth minute, Frank Velasquez scored his second in three games to give El Salvador the lead midway through the second period.
Luciano Franceschini equalized a half minute later and 15 second after that Jonathan Levi scored again to put Argentina ahead by the 20th minute.
Ruiz scored with a header and free kicks by Jose Membreno and Walter Torres restored El Salvador to the lead with 42 seconds remaining. Levi's second with 10 seconds left finished the scoring.