Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
738 views
in Technique[技术] by (71.8m points)

string - What is the use case for Ruby's %q / %Q quoting methods?

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|

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>]

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'
])

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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...