Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apart from "g", how to replace all characters from a string with a " "?

Tags:

ruby

How do I remove all characters, numbers and symbols except for "g" from a string and replace it with a " "?

string = "bi2gger 1is 00ggooder"
like image 634
Walter Shub Avatar asked Feb 05 '23 14:02

Walter Shub


1 Answers

gsub is overkill here. Use String#tr:

string = "bi2gger 1is 00ggooder"
string.tr("^g", " ")
# => "   gg         gg     "

This will return a new string. To instead modify the original string, use tr!.

See it on repl.it: https://repl.it/KJPY

like image 57
Jordan Running Avatar answered May 04 '23 00:05

Jordan Running