Escaping single and double quotes in a string in ruby?

How can I escape single and double quotes in a string?

I want to escape single and double quotes together. I know how to pass them separately but don't know how to pass both of them.

e.g: str = "ruby 'on rails" " = ruby 'on rails"

106355 次浏览
>> str = "ruby 'on rails\" \" = ruby 'on rails"
=> "ruby 'on rails" " = ruby 'on rails"

您可以使用 Q 字符串,它允许您使用任何您喜欢的分隔符:

str = %Q|ruby 'on rails" " = ruby 'on rails|

我的首选方法是不用担心转义,而是使用 %q,它的行为类似于单引号字符串(没有内插或字符转义) ,或者 %Q用于双引号字符串行为:

str = %q[ruby 'on rails" ] # like single-quoting
str2 = %Q[quoting with #{str}] # like double-quoting: will insert variable

查看 https://docs.ruby-lang.org/en/trunk/syntax/literals_rdoc.html#label-Strings并搜索 % strings

使用反斜杠转义字符

str = "ruby \'on rails\" "

下面是如何在更复杂的场景中使用 %Q[]的示例:

  %Q[
<meta property="og:title" content="#{@title}" />
<meta property="og:description" content="#{@fullname}'s profile. #{@fullname}'s location, ranking, outcomes, and more." />
].html_safe

如果我开始担心逃跑,我会选 Herdoc。它会帮你解决的:

string = <<MARKER
I don't have to "worry" about escaping!!'"!!
MARKER

MARKER delineates the start/end of the string. start string on the next line after opening the heredoc, then end the string by using the delineator again on it's own line.

这将完成所需的所有转义操作,并将其转换为双引号字符串:

string
=> "I don't have to \"worry\" about escaping!!'\"!!\n"

下面是一个完整的清单:

enter image description here

From http://learnrubythehardway.org/book/ex10.html

我会用: str = %(ruby 'on rails ") Because just % stands for double quotes(or %Q) and allows interpolation of variables on the string.

一个警告是:

使用 %Q[]%q[]进行字符串比较直观上是不安全的。

例如,如果加载某些表示空的内容,比如 ""'',则需要使用实际的转义序列。例如,假设 qvar等于 "",而不是任何空字符串。

这将评估为 false
if qvar == "%Q[]"

这个也一样,
if qvar == %Q[]

而这将评估为 true
if qvar == "\"\""

当从另一个堆栈向 Ruby 脚本发送命令行 vars 时,我遇到了这个问题。只有 Gabriel Augusto's answer为我工作。