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
truncateshould include the..., so lengths of 4 or greater should work perfectly.There appears to be a bug in the
String#truncatemethod. 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
4as the length, rails subtracts3for the..., leaving your adjusted length as1. So then rails uses that1as the ending part of a substring of “abcde”:However, if you supply
1as the length, after subtracting the3your adjusted length becomes-2. Plugging-2into the range gives you this: