Created
March 8, 2010 20:22
-
-
Save lzell/325620 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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