Rajneeta Srivastav
Rajneeta Srivastav

Reputation: 9

How can I escape the '@' character in ERB?

I am generating a Perl answer file using an Embedded Ruby code (ERB) template. This answer file contains variables which are then used to invoke an installer in silent mode.

I have no control over the installer code; what I do have control over is the answer file.

The installer throws an expected warning if the string contain unescaped metacharacters.

I want the answer file to have a Perl string constant containing the escape character. This value is fed using embedded Ruby code.

I have two variables. One is defined in Ruby and the other in Perl.

my $variable = <%= [@var].flatten %>;

$variable is in Perl and @var is Ruby.

@var will contain email addresses.

@var = "[email protected]"

I want to escape the at @ character so that Perl does not consider @gmail to be a variable.

In short, I want to write "abcd\@gmail.com" to the answer file.

I tried multiple things but in vain.

@var = "[email protected]"
@var.gsub("@", "\@") # => "[email protected]"
@var.gsub("@", "\\@") # => "abcd\\@gmail.com"
@var.gsub("@", "\\\@") # => "abcd\\@gmail.com"

Upvotes: 0

Views: 929

Answers (1)

Borodin
Borodin

Reputation: 126722

@var.gsub("@", "\\@") is correct. Ruby is representing the result as the equivalent double-quoted string which requires the backslash to be escaped

Try puts @var

Upvotes: 4

Related Questions