class String
def truncate_words(words_count, options = {})
'And they found that many people were sleeping better.'.truncate_words(5, omission: '... (continued)')
The last characters will be replaced with the :omission string (defaults to "..."):
# => "Once
upon
a
time
in..."
'Once
upon
a
time
in
a
world'.truncate_words(5, separator: '
')
Pass a string or regexp :separator to specify a different separator of words:
# => "Once upon a time..."
'Once upon a time in a world far far away'.truncate_words(4)
Truncates a given +text+ after a given number of words (words_count):
def truncate_words(words_count, options = {}) sep = options[:separator] || /\s+/ sep = Regexp.escape(sep.to_s) unless Regexp === sep if self =~ /\A((?>.+?#{sep}){#{words_count - 1}}.+?)#{sep}.*/m $1 + (options[:omission] || "...") else dup end end