Besides "g", how can I replace all characters in a string with ""?

How to remove all characters, numbers and symbols except "g"

from a string and replace it with " "

?

string = "bi2gger 1is 00ggooder"

      

+3
ruby


source to share


4 answers


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

+5


source to share


You can use String#gsub

with [^g]

, which replaces all characters except g

with " "

:



string.gsub(/[^g]/," ") #=> "   gg         gg     "

      

+2


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

0


source to share


The # gsub line can be used here.

string = "bi2gger 1is 00ggooder"

string.gsub(/./) { |s| s=='g' ? 'g' : ' ' }
  #=>    "   gg         gg     " 

      

0


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics