Matheus Mendes Matheus Mendes - 2 months ago 32
Ruby Question

Hide part of email domain

I'm trying to hide domain part of emails in my views when a user tries to reset the password, I'm using gsub but I'm having a problem with the union of 2 characters.

example:

"myemail@example.com".gsub(/.{0,4}@/,'####@')


I got this result:

"my###\#@example.com"


I don't wanna that \ in the middle of the ##, I entered the console and if I just write
'#@'

I got
"\#@"
, I don't know how to escape these characters.

with this method i also have a problem, if the domain is less then 4 letters i still put 4 '#'s in the domain. But my primary concern is about the junction of '#@'.

Answer

You're fine; the # is being escaped for you by irb or pry to disambiguate in its pretty print, since #@ can refer to interpolation of a global variable (see Why does string interpolation work in Ruby when there are no curly braces?). The backslash is not actually in the string, which you can verify by printing it explicitly:

print("myemail@example.com".gsub(/.{0,4}@/,'####@'))