Hakim al Umma Moulana Ashraf Ali Thanwi (Allah have mercy on him) once mentioned the following:
If a person is involved in sins, then one method for him to reform himself is that together with sincerely engaging in istighfaar and towbah, he should also impose some penalty upon himself so that this becomes a cause for him to refrain from falling into the sin in the future. This penalty can either be a physical penalty (e.g. fasting for a period of time) or a monetary penalty (i.e. giving a certain amount of money in sadaqah to the poor).
Our Prophet (Allah’s blessing & peace be upon him) mentioned in the Hadith that if a person says to someone (inviting him towards gambling), “Come, let me gamble with you,” then he should give some sadaqah.
In this Hadith, we see that Prophet (Allah’s blessing & peace be upon him) looked at the cause for one wishing to enter into the sin of gambling. The cause for this is the love for wealth. Therefore, he prescribed giving some sadaqah as a penalty, as this will cause the love for wealth to leave one’s heart (and this will also prevent him from falling into the sin in the future).
(Malfoozaat Hakeemul Ummat 23/378)