codecamp

百分比字面

  • 需要插值与嵌入双引号的单行字符串使用 %() (是 %Q 的简写)。多行字符串,最好用 heredocs 。

    # 差(不需要插值)
    %(<div class="text">Some text</div>)
    # 应该使用 '<div class="text">Some text</div>'
    
    # 差(没有双引号)
    %(This is #{quality} style)
    # 应该使用 "This is #{quality} style"
    
    # 差(多行)
    %(<div>\n<span class="big">#{exclamation}</span>\n</div>)
    # 应该是一个 heredoc
    
    # 好(需要插值、有双引号以及单行)
    %(<tr><td class="name">#{name}</td>)
  • 没有 ' 和 " 的字符串不要使用 %q。除非需要插值,否则普通字符串可读性更好。

    # 差
    name = %q(Bruce Wayne)
    time = %q(8 o'clock)
    question = %q("What did you say?")
    
    # 好
    name = 'Bruce Wayne'
    time = "8 o'clock"
    question = '"What did you say?"'
  • 只有正则表达式要匹配多于一个的 / 字元时,使用 %r

    # 差
    %r{\s+}
    
    # 好
    %r{^/(.*)$}
    %r{^/blog/2011/(.*)$}
  • 除非调用的命令中用到了反引号(这种情况不常见),否则不要用 %x 。

    # 差
    date = %x(date)
    
    # 好
    date = `date`
    echo = %x(echo `date`)
  • 不要用 %s 。社区倾向使用 :"some string" 来创建含有空白的符号。

  • 用 % 表示字面量时使用 (), %r 除外。因为 ( 在正则中比较常用。

    # 差
    %w[one two three]
    %q{"Test's king!", John said.}
    
    # 好
    %w(one tho three)
    %q("Test's king!", John said.)
正则表达式
元编程
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }