/ Tags: RUBY-CODE / Categories: SOLUTIONS

Truncate A String At A Word Boundary In Ruby Without Cutting Mid Word

Cutting a string at a fixed character count produces things like “The quick brown fo…”. Truncating at the last whole word before the limit reads properly and is what you want for previews, meta descriptions, and list summaries.

Description

Take the substring up to the limit, then cut back to the last whitespace. rindex(" ") finds it in one pass. Guard the case where there is no space inside the limit — a single very long word — by falling back to a hard cut. Strip trailing punctuation before appending the ellipsis so you don’t get “word,…”. ActiveSupport’s truncate accepts a separator: option that does the same thing, so in Rails you rarely need to hand-roll it.

Sample input:

  text = "Ruby makes text processing genuinely pleasant to write and read."
  truncate_words(text, 30)


Sample Output:

  # => "Ruby makes text processing…"

Answer

  def truncate_words(text, limit, omission: "…")
    return text if text.length <= limit

    window = limit - omission.length
    cut = text[0, window]
    boundary = cut.rindex(/\s/)

    truncated = boundary ? cut[0, boundary] : cut
    truncated.sub(/[[:punct:]]+\z/, "") + omission
  end

  truncate_words("Ruby makes text processing genuinely pleasant.", 30)
  # => "Ruby makes text processing…"

  truncate_words("Supercalifragilisticexpialidocious", 15)
  # => "Supercalifrag…"    (no space to fall back to)

  truncate_words("Short enough", 50)
  # => "Short enough"

  # Rails / ActiveSupport equivalent
  "Ruby makes text processing genuinely pleasant.".truncate(30, separator: " ")
  # => "Ruby makes text processing..."

Learn More

cdrrazan

Rajan Bhattarai

Full Stack Software Developer! 💻 🏡 Grad. Student, MCS. 🎓 Class of '23. GitKraken Ambassador 🇳🇵 2021/22. Works with Ruby / Rails. Photography when no coding. Also tweets a lot at TW / @cdrrazan!

Read More