Donato Donato - 6 months ago 25
Ruby Question

truncate text after exceeding certain size

Rails offers the

truncate
method when you want to truncate text that exceeds a certain character length. This is the example provided here:

truncate("Once upon a time in a world far far away")
# => "Once upon a time in a world..."


It truncates a given text after a given :length if text is longer than :length

But I have the following example:

str = "abcdefhijklmno"


After 12 characters I want it truncated, so the above text should look like this:

abcdefhijklm...


But I tried using the truncate method and cannot get the desired result:

> str = "abcdefhijklmno"
=> "abcdefhijklmno"
> str.truncate(15)
=> "abcdefhijklmno"
> str.truncate(14)
=> "abcdefhijklmno"
> str.truncate(13)
=> "abcdefhijk..."
> str.truncate(12)
=> "abcdefhij..."


I would think that
truncate(12)
would do it but it truncates after 9 characters. What am I doing wrong?

Answer

argument of truncate means size of output string (with "..."):

str.truncate(13)
=> "abcdefhijk..."
str.truncate(13).size
=> 13

You can change default omission(...) by empty space if you want:

str.truncate(13, omission: '')
=> "abcdefhijklmn"

More about Rails String#truncate here.

Comments