Besides "g", how can I replace all characters in a string with ""?
gsub
there is an excess. Use String#tr
:
string = "bi2gger 1is 00ggooder"
string.tr("^g", " ")
# => " gg gg "
This will return a new line. To change the original line instead, use tr!
.
Have a look at repl.it: https://repl.it/KJPY
source to share
You can use String#gsub
with [^g]
, which replaces all characters except g
with " "
:
string.gsub(/[^g]/," ") #=> " gg gg "
source to share
This can be achieved with regular expressions
This issue can be boiled down to regex as pointed out in the comments. To replace every "g" in your string, you can use a regular expression:/[^g]/
So the simplest solution is to use String#gsub
regexp to change all characters that match this rule. (Note that you also have a bang version of this method String#gsub!
, which will replace your original string)
You can read / try regular expressions on the site: RegexPal
source to share
The # gsub line can be used here.
string = "bi2gger 1is 00ggooder"
string.gsub(/./) { |s| s=='g' ? 'g' : ' ' }
#=> " gg gg "
source to share