Strange truncation behavior in rails 3

I am trying to use the String # truncate method provided by Rails 3:

irb(main):001:0> "abcde".truncate(1)
=> "abc..."
irb(main):002:0> "abcde".truncate(2)
=> "abcd..."
irb(main):003:0> "abcde".truncate(3)
=> "..."
irb(main):004:0> "abcde".truncate(4)
=> "a..."
irb(main):005:0> "abcde".truncate(5)
=> "abcde"
irb(main):006:0> "abcde".truncate(6)
=> "abcde"

I expect something like "a...", "ab...", "abc..."...

I do not understand why this is so.

I am using Ruby 1.8.7.

+5
source share
2 answers

The length you provide truncateshould include ..., so lengths of 4 or more should work fine.

There seems to be a mistake in the method String#truncate. Looking at the source code , it doesn't look like anything there to handle the provided lengths less than 3.

Example:

4 3 ..., 1. , rails 1 "abcde":

"abcde"[0...1] + '...'
# => "a..."

, 1 , 3 -2. -2 :

"abcde"[0...-2] + '...'
# => "abc..."
+4

:omission => ''

.

0

All Articles