From: Mark Thomas Date: 2008-08-20T05:16:33+09:00 Subject: Re: Cut a string if length > n On Aug 19, 11:25 am, Pål Bergström wrote: > What's the best way to cut a string if the length is above n characters? > Is it slice, or is there any other convenient method? Trying to > understand the string class from the docs but not sure which one to use. 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.