Hi! Thanks for visiting my blog. If you've received any value from my content would you mind supporting my new startup by downloading our browser add-on? It's called PriceBlink and makes online shopping a breeze. You can watch it in action here and download it for Chrome, Firefox, IE, or Safari by going to PriceBlink.com. Thank you and I hope you enjoy!

Truncating Text with Ruby on Rails

Aug 27

Truncating text is a very handy utility when building web applications. This can come into play when displaying part of a blog post, forum post, comments, and so on. Luckily, Ruby on Rails has a nifty built-in helper method, intuitively named truncate. Let’s say you have the following string:

Hello, this is my first blog post!

and let’s say you’ve assigned it to a variable called @post. In you view template you could then truncate using:

truncate @post, 20

This would yield:

Hello, this is my…

If you’re so inclined to count the characters you’ll realize there’s only seventeen with “…” accounting for the last three. This can be fixed by specifying a third parameter to the truncate method:

truncate @post, 20, “”

The third parameter is actually a custom string that you can tell Ruby to append to your truncated string. Just remember that it actually counts in your total character count so take this into consideration. Here’s an example:

truncate @post, 23, “!!!”

which yields

Hello, this is my fi!!!

Personally, I don’t feel that three characters cause that big of a difference when dealing with something as inexact as truncating text. Yet, if the situation calls for exactness then be sure to take this into consideration.

Leave a Reply