需要插值與嵌入雙引號的單行字串使用 %() (是 %Q 的簡寫)。多行字串,最好用 heredocs 。
# bad (no interpolation needed) %(<div class="text">Some text</div>) # should be '<div class="text">Some text</div>' # bad (no double-quotes) %(This is #{quality} style) # should be "This is #{quality} style" # bad (multiple lines) %(<div>\n<span class="big">#{exclamation}</span>\n</div>) # should be a heredoc. # good (requires interpolation, has quotes, single line) %(<tr><td class="name">#{name}</td>)
沒有 ' 和 " 的字串不要使用 %q 。除非許多字元需要轉義,否則一般字元串可讀性更好。
# bad name = %q(Bruce Wayne) time = %q(8 o'clock) question = %q("What did you say?") # good name = 'Bruce Wayne' time = "8 o'clock" question = '"What did you say?"'
%r 的方式只適合於定義包含多個 / 符號的Regex。
# bad %r(\s+) # still bad %r(^/(.*)$) # should be /^\/(.*)$/ # good %r(^/blog/2011/(.*)$)
除非調用的命令中用到了反引號(這種情況不常見),否則不要用 %x。
# bad date = %x(date) # good date = `date` echo = %x(echo `date`)
不要用 %s 。社區傾向使用 :"some string" 來建立含有空白的符號。
用 % 表示字面量時使用 (), %r 除外。因為大括弧經常出現在Regex在很多情境中在很多情境中不太通用的字元例如 { 作為分割符可能是一個更好的選擇,取決於正則式的內容。
# bad %w[one two three] %q{"Test's king!", John said.} # good %w(one two three) %q("Test's king!", John said.)