简体   繁体   English

字符串文字,无需转义反斜杠

[英]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#中,我可以写反斜杠和其他特殊字符,而不必在字符串前使用@进行转义,但是我必须转义双引号。

C# 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}" . 在Ruby中,我可以使用单引号字符串文字,但是我想将其与"text #{value}"类的字符串插值结合使用。 Is there an equivalent in Ruby to @ in C#? Ruby中的等效于C#中的@吗?

There is somewhat similar thing available in Ruby. Ruby中有一些类似的东西。 Eg 例如

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 高温超导

You can use heredoc with single quotes. 您可以将heredoc与单引号一起使用。

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. 如果要在末尾消除换行符,请chomp它。

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"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM