开发者

Strange Behavior of Truncate in Rails 3

开发者 https://www.devze.com 2023-03-07 05:54 出处:网络
I\'ve been trying the String#truncate method provided by Rails 3: irb(main):001:0> \"abcde\".truncate(1)

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> 开发者_如何学JAVA"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..."


You can enforce the expected behaviour passing

:omission => ''

to truncate.

0

精彩评论

暂无评论...
验证码 换一张
取 消