Never been to DZone Snippets before?

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 (See related posts)

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 on this post

rpheath posts on Oct 08, 2007 at 19:26
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

You need to create an account or log in to post comments to this site.


Click here to browse all 4858 code snippets

Related Posts