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

前端 未结 5 1122
一向
一向 2020-12-02 08:44

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 the

5条回答
  •  不知归路
    2020-12-02 09:01

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

    link = %q[link]
    

    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.

提交回复
热议问题