百分比字面量 (Percent Literals)

优质
小牛编辑
131浏览
2023-12-01
  • 统一用圆括号,不要用其他括号, 因为它的行为更接近于一个函数调用。

    # 错误
    %w[date locale]
    %w{date locale}
    %w|date locale|
    
    # 正确
    %w(date locale)
  • 随意用 %w

    STATES = %w(draft open closed)
  • 在一个单行字符串里需要 插值(interpolation) 和内嵌双引号时使用 %()。 对于多行字符串,建议用 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>)
  • 仅在需要匹配 多于一个 '/'符号的时候使用 %r

    # 错误
    %r(\s+)
    
    # 依然不好
    %r(^/(.*)$)
    # should be /^\/(.*)$/
    
    # 正确
    %r(^/blog/2011/(.*)$)
  • 避免使用 %x ,除非你要调用一个带引号的命令(非常少见的情况)。

    # 错误
    date = %x(date)
    
    # 正确
    date = `date`
    echo = %x(echo `date`)