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 。除非許多字符需要轉(zhuǎn)義,否則普通字符串可讀性更好。
# 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 的方式只適合于定義包含多個(gè) / 符號的正則表達(dá)式。
# bad %r(\s+) # still bad %r(^/(.*)$) # should be /^\/(.*)$/ # good %r(^/blog/2011/(.*)$)
除非調(diào)用的命令中用到了反引號(這種情況不常見),否則不要用 %x。
# bad date = %x(date) # good date = `date` echo = %x(echo `date`)
不要用 %s 。社區(qū)傾向使用 :"some string" 來創(chuàng)建含有空白的符號。
用 % 表示字面量時(shí)使用 (), %r 除外。因?yàn)榇罄ㄌ柦?jīng)常出現(xiàn)在正則表達(dá)式在很多場景中在很多場景中不太通用的字符例如 { 作為分割符可能是一個(gè)更好的選擇,取決于正則式的內(nèi)容。
# bad
%w[one two three]
%q{"Test's king!", John said.}
# good
%w(one two three)
%q("Test's king!", John said.)
相關(guān)文章
Ruby實(shí)現(xiàn)的最短編輯距離計(jì)算方法
這篇文章主要介紹了Ruby實(shí)現(xiàn)的最短編輯距離計(jì)算方法,本文直接給出實(shí)現(xiàn)代碼,需要的朋友可以參考下2015-05-05
使用Ruby來編寫訪問Twitter的命令行應(yīng)用程序的教程
這篇文章主要介紹了使用Ruby來編寫訪問Twitter的命令行應(yīng)用程序的教程,文章來自于IBM官方網(wǎng)站技術(shù)文檔,需要的朋友可以參考下2015-04-04

