2

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 '#@'.

Matheus Mendes
  • 155
  • 2
  • 14

2 Answers2

1

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}@/,'####@'))
Community
  • 1
  • 1
0

If @, as part of @example, is not escaped and is preceded by '#', Ruby inserts the value of the instance variable @example.

Suppose:

@example = 'hi'
"my####@example.com" #=> "my###.com"

If there is no instance variable @example, referencing it returns nil, which is converted to an empty string.

"my####@example.com" #=> "my###.com"

This can also be done with global variables:

$example = 'ho'
"my####$example.com" #=> "my###ho.com"

and with class variables:

@@example = 'hum'
"my####@@example.com" #=> "my###hum.com"
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100