All perfect praise be to Allah, The Lord of the Worlds. I testify that there is none worthy of worship except Allah, and that Muhammad is His slave and Messenger.
Masturbation is Haram (prohibited). We advise you, as a young man, not to stain your account of deeds with sins and disobedience. Rather, you should fill it with obedience to Allah, the Almighty; youth is one of the most important stages of life for which you will be held accountable on the Day of Resurrection. According to an authentic Hadith: “The feet of the son of Adam shall not move from before his Lord on the Day of Judgment, until he is asked about five things: About his life and how he spent it, about his youth and how he spent it, about his wealth and how he earned it, and spent it upon, and what he did with what he knew.” [ At-Tirmidhi]
As for the ruling on masturbation while fasting, it does not invalidate the fast unless ejaculation occurs, in which case it is mandatory to make up for that fast and make Ghusl (ritual bath).
However, if you ejaculated without knowing that masturbation is forbidden, your fast is valid according to the view we adopt here in Islamweb. Given that situation, you should make up that fast as a precaution. As for ghusl, it is obligatory in any case if semen is discharged.
Allah knows best.