Skip to content

Instantly share code, notes, and snippets.

@marvin
Created June 7, 2011 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marvin/1013275 to your computer and use it in GitHub Desktop.
Save marvin/1013275 to your computer and use it in GitHub Desktop.
helper to truncate words
def truncate_words(text, length, end_string = ' ...')
words = text.split()
words = words[0..(length-1)].join(' ') + (words.length > length ? end_string : '')
end
@marvin
Copy link
Author

marvin commented Jun 7, 2011

I used this in a current sinatra project to cut the length of a task title that is shown in a task preview
use it like that

truncate_words("a very very long long title", 3, '...')

will cut it down to only show the first 3 words

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment