In Ruby on Rails, there are two main methods for truncating strings provided by Active Support: truncate_words
and truncate
. Both methods take a string as their argument, but they have different behaviors.
truncate_words
The truncate_words
method truncates a string to a specified number of words. It can be customized with :omission
and :separator
options.
For example, the following code truncates the string “This is a very long string” to three words.
1
2
3
str = "This is a very long string"
str.truncate_words(3)
# => "This is a..."
By default, the spaces between the words are considered the separator.
Take a look at this other example, where the separator is “/”. If we don’t pass the :separator
option, the string will be separated by the spaces.
1
2
3
str = "This is / a very / long / string"
str.truncate_words(3)
# => "This is /..."
Using :separator
In this case, we are passing the / as :separator
:
1
2
3
str = "This is / a very / long / string"
str.truncate_words(3, separator: '/')
# => "This is / a very / long ..."
We can also use regex:
1
2
3
str = "This is a very long string"
str.truncate_words(3, separator: /\s/)
# => "This is a..."
Using :omission
In this example, the :omission
option is used to customize the truncation indicator. The default truncation indicator is “…”, but this can be changed to any string.
1
2
3
str = "This is a very long string"
str.truncate_words(5, omission: '&to be continued')
# => "This is a very long&to be continued"
1
2
3
str = "This is a very long string"
str.truncate_words(5, omission: '!!!!!')
# => "This is a very long!!!!!"
The truncate_words
method is a good option for truncating strings to a specific number of words while ensuring that the string is truncated at a word boundary.
truncate
The truncate
method truncates a string to a specified number of characters that is length
. It also has :omission
and :separator
as argument options.
1
2
3
str = "This is a very long string"
str.truncate(22)
# => "This is a very long..."
Using :separator
1
2
3
str = "This is a very long string"
str.truncate(22, separator: ' ')
# => "This is a very long..."
Using :omission
1
2
3
str = "This is a very long string"
str.truncate(22, omission: '&to be continued;')
# => "This &to be continued;"