DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Truncate Text With Word Boundaries In Ruby

10.12.2005
| 18760 views |
  • submit to reddit
        
  def truncate_words(text, length = 30, end_string = ' …')
    words = text.split()
    words[0..(length-1)].join(' ') + (words.length > length ? end_string : '')
  end
    

Comments

Snippets Manager replied on Tue, 2008/10/07 - 3:00pm

I think it's good to return if text is nil (or blank in Rails) def truncate_words(text, length = 30, end_string = ' …') return if text == nil words = text.split() words[0..(length-1)].join(' ') + (words.length > length ? end_string : '') end