需要插值與嵌入雙引號的單行字符串使用 %() (是 %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 的方式只適合于定義包含多個 / 符號的正則表達式。
# 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 除外。因為大括號經常出現在正則表達式在很多場景中在很多場景中不太通用的字符例如 { 作為分割符可能是一個更好的選擇,取決于正則式的內容。
# bad %w[one two three] %q{"Test's king!", John said.} # good %w(one two three) %q("Test's king!", John said.)
新聞熱點
疑難解答
圖片精選