instance method
truncate_words
Ruby on Rails 6.0.6
Since v4.2.9Signature
truncate_words(words_count, options = {})
Truncates a given text after a given number of words (words_count):
'Once upon a time in a world far far away'.truncate_words(4) # => "Once upon a time..."
Pass a string or regexp :separator to specify a different separator of words:
'Once<br>upon<br>a<br>time<br>in<br>a<br>world'.truncate_words(5, separator: '<br>') # => "Once<br>upon<br>a<br>time<br>in..."
The last characters will be replaced with the :omission string (defaults to “…”):
'And they found that many people were sleeping better.'.truncate_words(5, omission: '... (continued)') # => "And they found that many... (continued)"
Parameters
-
words_countreq -
optionsopt = {}
Source
# File activesupport/lib/active_support/core_ext/string/filters.rb, line 136
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
Defined in activesupport/lib/active_support/core_ext/string/filters.rb line 136
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in String