instance method truncate_words

Ruby on Rails 8.0.4

Since v4.2.9

Available in: v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

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_count req
options opt = {}
Source
# File activesupport/lib/active_support/core_ext/string/filters.rb, line 142
  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 142 · View on GitHub · Improve this page · Find usages on GitHub

Defined in String

Type at least 2 characters to search.

↑↓ navigate · open · esc close