Truncate portions of a string to limit the whole string's length in Ruby

Posted by Horace Loeb on Stack Overflow See other posts from Stack Overflow or by Horace Loeb
Published on 2010-06-06T21:09:45Z Indexed on 2010/06/06 21:42 UTC
Read the original article Hit count: 281

Filed under:
|

Suppose you want to generate dynamic page titles that look like this:

"It was all a dream, I used to read word up magazine" from "Juicy" by The Notorious B.I.G

I.e., "LYRICS" from "SONG_NAME" by ARTIST

However, your title can only be 69 characters total and this template will sometimes generate titles that are longer.

One strategy for solving this problem is to truncate the entire string to 69 characters. However, a better approach is to truncate the less important parts of the string first. I.e., your algorithm might look something like this:

  1. Truncate the lyrics until the entire string is <= 69 characters
  2. If you still need to truncate, truncate the artist name until the entire string is <= 69 characters
  3. If you still need to truncate, truncate the song name until the entire string is <= 69 characters
  4. If all else fails, truncate the entire string to 69 characters

Ideally the algorithm would also limit the amount each part of the string could be truncated. E.g., step 1 would really be "Truncate the lyrics to a minimum of 10 characters until the entire string is <= 69 characters"

Since this is such a common situation, I was wondering if someone has a library or code snippet that can take care of it.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about string-manipulation