Ruby中百分比符號和字面值的使用樣本_ruby專題

來源:互聯網
上載者:User

    需要插值與嵌入雙引號的單行字串使用 %() (是 %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.)


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.