Donato Donato - 7 months ago 31
Ruby Question

truncate text after exceeding certain size

Rails offers the

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:


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
would do it but it truncates after 9 characters. What am I doing wrong?


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

=> "abcdefhijk..."
=> 13

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

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

More about Rails String#truncate here.