Connor Renfree put the gun in a sock before repeatedly hitting the victim on the head during a game of table tennis at Wetherby YOI.
Renfree, 18, once carried out a similar attack on another inmate at Wetherby YOI and blinded him with one eye.
Renfree was given an extended sentence totaling seven years for the latest offense.
Bashir Ahmed, the prosecutor, said Renfree was 17 years old at the time of the November 26 attack last year.
The incident happened at 6.30 p.m. during the time of the association of detainees in a common area.
Mr Ahmed said Renfree armed himself with the improvised weapon he hid on the front of his pants.
He attacked the victim from behind while playing table tennis.
Renfree punched the inmate on the head and back before he was removed by prison officers.
The victim had to be taken to Harrogate hospital to have stitches on a head injury.
He also had bruises on his back and body.
Renfree pleaded guilty to intentionally injuring.
At the time of the incident, he was serving a four-year sentence for attacking an inmate with spray deodorant hidden in a sock.
The victim of this attack was permanently blinded in one eye.
Wetherby YOI Governor David Pearce gave a statement to the court describing how the attack had a “devastating impact” on inmates and facility staff.
Adam Lodge, mitigating, said: “He was not taking his medication for a personality disorder and believed the victim was a sex offender and had violent sex urges against him.
“The accused admits that he has a problem with his temperament and his violent impulses, which is very worrying for a man of his younger years.”
Renfree was sentenced to an extended sentence of a total of seven years after being found to be dangerous.
He must serve a four-year detention period followed by an extended three-year license period.