Skip to content

How to truncate text in Ruby on Rails

Posted on 14 August 2006

It's really simple to truncate text in Rails, just pass the function the text, the max number of characters you want to show and a truncate string you want to display instead of the last 3 characters.

truncate(category.description, 40, "...")

View the snippets archive ››

4 comments made

Chris Kampmeier commented on 22 Jan 07 at 20:40

You’d probably be happier with something like this, which will cut off text at a word boundary. You can put it in your application helper to use it in all your views.

def snippet(thought)
wordcount = 10
thought.split[0..(wordcount-1)].join(” “) + (thought.split.size > wordcount ? ”...” : ””)
end

Byron Bowerman commented on 30 Nov 07 at 16:53

@Chris thanks, I’m gunna use this. However, I modified it so that the wordcount is passable as a parameter:

def snippet(thought, wordcount) thought.split[0..(wordcount-1)].join(" ") +(thought.split.size > wordcount ? "..." : "") end

Also, just an fyi, when I pasted your code into Textmate it preserved the fancy quotes, which gave me about 30 seconds of WTF?

lou commented on 06 Dec 07 at 21:42

Try this one out, the number in brackets is the number of chars to match:

thought.gsub(/^(.{10}[\w.])(.)/) {$2.empty? ? $1 : $1 + ’...’}

It doesn’t break words and adds ’...’ if necessary. Check out www.golark.com and click submit to really be impressed with the power of regex.

lou commented on 06 Dec 07 at 21:46

Great, it took the asterisks out. Replace the a’s in the following string with asterisks:

thought.gsub(/^(.{10}[\w.]a)(.a)/) {$2.empty? ? $1 : $1 + ’...’}

Got something to say?

About

Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.

Contact

my name at gmail.com

More snippets

Take a look in the archive

Need a website?

Contact my employer. Make sure to check out our portfolio of work.

Hosting

I recommend hostingrails.com