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.
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..."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With