Sofia Braun Sofia Braun - 3 months ago 21
Ruby Question

Improper gsub replacement

I am trying to replace all alphanumeric characters of an email with the '#' character using the

gsub
method but Ruby is inserting a backslash before the '@' character.

E.g:

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

Answer

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

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

What you see in IRB/Pry is the prevention of #@ being interpreted as string interpolation.

Please also refer to very valuable comment by @Stefan below.

Comments