Rails 3 中截断的奇怪行为
我一直在尝试 Rails 3 提供的 String#truncate 方法:
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"
我期待类似 "a..."
, "ab..."
, “abc...”
...
我不明白为什么它会这样。
我正在使用 Ruby 1.8.7。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您提供给
truncate
的长度应包括...
,因此 4 或更大的长度应该可以完美工作。String#truncate
方法中似乎存在错误。查看源代码 ,看起来没有任何东西可以处理提供的小于 3 的长度。示例:
当您提供
4
作为长度时,rails 会减去3
作为长度...
,将调整后的长度保留为1
。因此,rails 使用1
作为“abcde”子字符串的结尾部分:但是,如果您提供
1
作为长度,则在减去3< /code> 调整后的长度变为
-2
。将-2
插入该范围即可得到: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 subtracts3
for the...
, leaving your adjusted length as1
. So then rails uses that1
as the ending part of a substring of "abcde":However, if you supply
1
as the length, after subtracting the3
your adjusted length becomes-2
. Plugging-2
into the range gives you this:您可以强制传递截断的预期行为
。
You can enforce the expected behaviour passing
to truncate.