Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange Behavior of Truncate in Rails 3

I've been trying 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 am expecting something like "a...", "ab...", "abc..."...

I don't understand why it is acting like this.

I'm using Ruby 1.8.7.

like image 212
Andrew Liu Avatar asked Oct 12 '22 00:10

Andrew Liu


1 Answers

The length you provide to truncate should include the ..., so lengths of 4 or greater should work perfectly.

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

Example:

When you supply 4 as the length, rails subtracts 3 for the ..., leaving your adjusted length as 1. So then rails uses that 1 as the ending part of a substring of "abcde":

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

However, if you supply 1 as the length, after subtracting the 3 your adjusted length becomes -2. Plugging -2 into the range gives you this:

"abcde"[0...-2] + '...'
# => "abc..."
like image 51
Dylan Markow Avatar answered Oct 14 '22 08:10

Dylan Markow