Michael
Michael

Reputation: 1622

String literal without need to escape backslash

In C#, I can write backslashes and other special characters without escaping by using @ before a string, but I have to escape double-quotes.

C#

string foo = "The integer division operator in VisualBASIC is written \"a \\ b\"";
string bar = @"The integer division operator in VisualBASIC is written \"a \ b\""

In Ruby, I could use the single-quote string literal, but I'd like to use this in conjuction with string interpolation like "text #{value}". Is there an equivalent in Ruby to @ in C#?

Upvotes: 9

Views: 5670

Answers (2)

sawa
sawa

Reputation: 168081

You can use heredoc with single quotes.

foo = <<'_'
The integer division operator in VisualBASIC is written "a \ b";
_

If you want to get rid of the newline character at the end, then chomp it.

Note that this does not work with string interpolation. If you want to insert evaluated expressions within the string, you can use % operation after you create the string.

foo = <<'_'
text %{value}
_

foo.chomp % {value: "foo"}

Upvotes: 7

Harsh Gupta
Harsh Gupta

Reputation: 4538

There is somewhat similar thing available in Ruby. E.g.

foo = %Q(The integer division operator in VisualBASIC is written "a \\ b" and #{'interpolation' + ' works'})

You can also interpolate strings in it. The only caveat is, you would still need to escape \ character.

HTH

Upvotes: 12

Related Questions