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
Elegant Way Of Shorten A Text String
this method shortens a plain text string down to complete words contained in given scope (count)
def shorten (string, count = 30)
if string.length >= count
shortened = string[0, count]
splitted = shortened.split(/\s/)
words = splitted.length
splitted[0, words-1].join(" ") + ' ...'
else
string
end
end






Comments
Snippets Manager replied on Fri, 2009/02/20 - 8:17am
Ryan Heneise replied on Thu, 2007/12/20 - 2:36pm
def shorten (string, word_limit = 5) words = string.split(/\s/) if words.size >= word_limit last_word = words.last words[0,(word_limit-1)].join(" ") + '...' + last_word else string end end shorten("Here's another implementation of that, which also allows the user to specify the ending", 7) => "Here's another implementation of that, which...ending"Ryan Heneise replied on Thu, 2007/12/20 - 2:36pm
John Griffiths replied on Mon, 2007/07/23 - 7:25am
Snippets Manager replied on Mon, 2007/10/08 - 7:20pm
def truncate_words(text, length, end_string = ' ...') returning words = text.split() do words = words[0..(length-1)].join(' ') + (words.length > length ? end_string : '') end end