Percent Literals

  • Prefer parentheses over curly
    braces, brackets, or pipes when using %-literal delimiters for
    consistency, and because the behavior of %-literals is closer to method
    calls than the alternatives.[link]

    1. # bad
    2. %w[date locale]
    3. %w{date locale}
    4. %w|date locale|
    5. # good
    6. %w(date locale)
  • Use %w freely.[link]

    1. STATES = %w(draft open closed)
  • Use %() for single-line strings which require
    both interpolation and embedded double-quotes. For multi-line strings,
    prefer heredocs.[link]

    1. # bad - no interpolation needed
    2. %(Welcome, Jane!)
    3. # should be 'Welcome, Jane!'
    4. # bad - no double-quotes
    5. %(This is #{quality} style)
    6. # should be "This is #{quality} style"
    7. # bad - multiple lines
    8. %(Welcome, Jane!\nPlease enjoy your stay at #{location}\nCheers!)
    9. # should be a heredoc.
    10. # good - requires interpolation, has quotes, single line
    11. %(Welcome, #{name}!)
  • Use %r only for regular expressions matching more
    than
    one ‘/‘ character.[link]

    1. # bad
    2. %r(\s+)
    3. # still bad
    4. %r(^/(.*)$)
    5. # should be /^\/(.*)$/
    6. # good
    7. %r(^/blog/2011/(.*)$)
  • Avoid the use of %x unless you’re going to invoke a
    command with backquotes in it (which is rather unlikely).
    [link]

    1. # bad
    2. date = %x(date)
    3. # good
    4. date = `date`
    5. echo = %x(echo `date`)