From: "Pål Bergström" Date: 2008-08-20T05:21:52+09:00 Subject: Re: Cut a string if length > n Mark Thomas wrote: > Rails has a utf8-compatible helper called truncate, called like so: > > truncate(text, length = 30, truncate_string = "...") > If text is longer than length, text will be truncated to the length of > length (defaults to 30) and the last characters will be replaced with > the truncate_string (defaults to "..."). > > And the implementation is: > > def truncate(text, length = 30, truncate_string = "...") > if text > l = length - truncate_string.chars.length > chars = text.chars > (chars.length > length ? chars[0...l] + truncate_string : > text).to_s > end > end > > Where chars is a string method in Ruby 1.8.7 or greater. Perfect :-) -- Posted via http://www.ruby-forum.com/.