Incorrect gsub replacement

I am trying to replace all alphanumeric characters of a letter with the character “#” using the gsub method, but Ruby inserts a backslash before the “@” character.

eg:

" john@doe.com ".gsub(/[a-z0-9]/, "#") returns "###\#@###.###" instead of "####@###.###" .

+5
source share
2 answers

It returns "####@###.###" , as expected, to try:

 puts " john@doe.com ".gsub(/[a-z0-9]/, "#") 

What you see in IRB / Pry is to prevent #@ interpreting as string interpolation.

Please refer to @Stefan's very valuable comment below.

+8
source

tr faster than gsub :

 puts " foo@bar.com ".tr('a-zA-Z0-9', '#') # >> ###@###.### 
+3
source

All Articles