Truncating Text with Ruby on Rails



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