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

Elegant Way Of Shorten A Text String

09.27.2007
| 23598 views |
  • submit to reddit
        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

why not just use the built in helper method truncate? http://www.railsbrain.com/api/rails-2.2.2/doc/index.html?a=M002156&name=truncate truncate("This is some text", :length => 14) you can set the ... to something else by using the omission option

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

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"

John Griffiths replied on Mon, 2007/07/23 - 7:25am

excellent, made my day, good work guys!

Snippets Manager replied on Mon, 2007/10/08 - 7:20pm

Here's another implementation of that, which also allows the user to specify the ending... 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