Skip to content

Instantly share code, notes, and snippets.

@lzell
Created March 8, 2010 20:22
Show Gist options
  • Save lzell/325620 to your computer and use it in GitHub Desktop.
Save lzell/325620 to your computer and use it in GitHub Desktop.
module Truncate
# only add ellipsis on a word boundary, do not break a word
def truncate(char_num)
# return a new string
self.gsub(/((?:.|\n){#{char_num}}[\w.]*)((?:.|\n)*)/) {$2.empty? ? $1 : $1 + '...'}
end
end
class String
include Truncate
end
"hello world".truncate(3) #=> "hello..."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment