Strings

  • Prefer string interpolation instead of
    string concatenation:[link]

    1. # bad
    2. email_with_name = user.name + ' <' + user.email + '>'
    3. # good
    4. email_with_name = "#{user.name} <#{user.email}>"

    Furthermore, keep in mind Ruby 1.9-style interpolation. Let’s say you are
    composing cache keys like this:

    1. CACHE_KEY = '_store'
    2. cache.write(@user.id + CACHE_KEY)

    Prefer string interpolation instead of string concatenation:

    1. CACHE_KEY = '%d_store'
    2. cache.write(CACHE_KEY % @user.id)
  • Avoid using String#+ when you need to
    construct large data chunks. Instead, use String#<<. Concatenation mutates
    the string instance in-place and is always faster than String#+, which
    creates a bunch of new string objects.[link]

    1. # good and also fast
    2. story = ''
    3. story << 'The Ugly Duckling'
    4. paragraphs.each do |paragraph|
    5. story << paragraph
    6. end
  • Use \ at the end of the line instead of +
    or << to concatenate multi-line strings.
    [link]

    1. # bad
    2. "Some string is really long and " +
    3. "spans multiple lines."
    4. "Some string is really long and " <<
    5. "spans multiple lines."
    6. # good
    7. "Some string is really long and " \
    8. "spans multiple lines."