Strings

Strings

  • Prefer string interpolation instead of
    string concatenation:[link]
  # bad
  email_with_name = user.name + ' <' + user.email + '>'

  # good
  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:

  CACHE_KEY = '_store'

  cache.write(@user.id + CACHE_KEY)

Prefer string interpolation instead of string concatenation:

  CACHE_KEY = '%d_store'

  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]
  # good and also fast
  story = ''
  story << 'The Ugly Duckling'

  paragraphs.each do |paragraph|
    story << paragraph
  end
  • Use \ at the end of the line instead of +
    or << to concatenate multi-line strings.
    [link]
  # bad
  "Some string is really long and " +
    "spans multiple lines."

  "Some string is really long and " <<
    "spans multiple lines."

  # good
  "Some string is really long and " \
    "spans multiple lines."