Ruby中百分號和字面值的使用示例
更新時間:2015年08月03日 16:25:57 投稿:goldensun
這篇文章主要介紹了Ruby中百分號和字面值的使用示例,作者給出了相關編程風格上的一些建議,需要的朋友可以參考下
需要插值與嵌入雙引號的單行字符串使用 %() (是 %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 。社區(qū)傾向使用 :"some string" 來創(chuàng)建含有空白的符號。
用 % 表示字面量時使用 (), %r 除外。因為大括號經常出現(xiàn)在正則表達式在很多場景中在很多場景中不太通用的字符例如 { 作為分割符可能是一個更好的選擇,取決于正則式的內容。
# bad
%w[one two three]
%q{"Test's king!", John said.}
# good
%w(one two three)
%q("Test's king!", John said.)

