Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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#?

like image 323
Michael Avatar asked Mar 18 '15 13:03

Michael


People also ask

How do I ignore an escape character in a string?

An escape sequence is a set of characters used in string literals that have a special meaning, such as a new line, a new page, or a tab. For example, the escape sequence \n represents a new line character. To ignore an escape sequence in your search, prepend a backslash character to the escape sequence.

How do you handle a backslash in a string?

If you want to include a backslash character itself, you need two backslashes or use the @ verbatim string: var s = "\\Tasks"; // or var s = @"\Tasks"; Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.

How do I fix unterminated string literal Python?

To fix this error, check if: you have opening and closing quotes (single or double) for your string literal, you have escaped your string literal correctly, your string literal isn't split across multiple lines.


2 Answers

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

like image 144
Harsh Gupta Avatar answered Oct 13 '22 22:10

Harsh Gupta


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"}
like image 37
sawa Avatar answered Oct 13 '22 23:10

sawa