Ruby 的 %q/%Q 引用方法的用例是什么? [英] What is the use case for Ruby's %q / %Q quoting methods?

查看:61
本文介绍了Ruby 的 %q/%Q 引用方法的用例是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读 Thomas 的 Programming Ruby 1.9,并发现了替代的分隔单引号和双引号方法(%q/%Q).我也从其他 Ruby 语言参考资料中了解到它们.

I've been reading through Thomas' Programming Ruby 1.9 and came upon the alternative delimited single and double-quoting methods (%q / %Q). I've known of them from other Ruby language references as well.

%q/I'm acting like a single-quoted string/

%Q|"I'm acting like a double-quoted string" --Anonymous|

我使用 Ruby 的时间不长,但我从未在生产代码中遇到过这种引用方法.

I have not been working with Ruby for long, but I have never encountered this quoting method in production code.

除了使用反斜杠避免内部转义引号的明显能力外,这种通过常规单引号或双引号引用的方法的常见用例是什么?它们通常用于单行还是多行字符串?如果在多行字符串中使用,它们是否比 HEREDOC 字符串更受青睐?是否有一个特别的 Ruby 习语?

Other than the obvious ability to avoid internally escaping quotes with backslashes, what are the common use cases for this method of quoting over regular single or double quotes? Are they typically used in single or multiline strings? If used in multiline strings, are they ever favored over HEREDOC strings? Is there a particular Ruby idiom where they're commonly found?

推荐答案

它们对于在您已经用完"引用方法的情况下使用 JavaScript 转义 HTML 非常有用:

They're extraordinarily useful for escaping HTML with JavaScript in it where you've already "run out" of quoting methods:

link = %q[<a href="javascript:method('call')">link</a>]

我还发现它们在处理多行 SQL 语句时非常有用:

I've also found them to be very useful when working with multi-line SQL statements:

execute(%Q[
  INSERT INTO table_a (column_a)
    SELECT value
      FROM table_b
      WHERE key='value'
])

优点是您无需注意查询中使用的引用类型.它适用于单人、双人或两者.它们也比 HEREDOC 风格的方法少很多麻烦.

The advantage there is you don't need to pay attention to the type of quoting used within your query. It will work with either single, double, or both. They're also a lot less fuss than the HEREDOC style method.

Ruby 提供了其他类似的便捷方法,例如可以构造正则表达式的 %r.当试图编写一个处理诸如 http:// 之类的东西时,这避免了斜线炎,否则就必须转义.

Ruby provides other convenience methods like this such as %r which can construct regular expressions. That avoids slash-itis when trying to write one that handles stuff like http:// that would otherwise have to be escaped.

这篇关于Ruby 的 %q/%Q 引用方法的用例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆