2008年6月9日星期一

truncate(截取字符串)

ActionView::Helpers::TextHelper#truncate(text, length = 30, truncate_string = "...")
截取过长字符串,省略部分用truncate_string来代替(默认是...)。

If text is longer than length, text will be truncated to the length of length (defaults to 30) and the last characters will be replaced with the truncate_string (defaults to "…").

Examples

truncate("Once upon a time in a world far far away", 14)
# => Once upon a...

truncate("Once upon a time in a world far far away")
# => Once upon a time in a world f...

truncate("And they found that many people were sleeping better.", 25, "(clipped)")
# => And they found that many (clipped)

truncate("And they found that many people were sleeping better.", 15, "... (continued)")
# => And they found... (continued)


length = 显示的字符串长度 + truncate_string的长度,也就是说,设置length为10,实际显示的字符数是7个,还有3个是用来显示...的。
当然,如果结束符用其他的(比如......),那实际显示的字符串长度就是3个了。

源代码:
def truncate(text, length = 30, truncate_string = "...")
if text.nil? then return end
l = length - truncate_string.chars.length
(text.chars.length > length ? text.chars[0...l] + truncate_string : text).to_s
end
length的长度必须要大于truncate_string的长度,如有必要,在调用truncate方法前我们应该自己先判断一下。
这个截取方法对于中英文字符都有效,因为chars方法返回的是UTF-8的结果。

不过这样也带来了另一个问题,就是截取同样多的字符时,中文比英文显得要长一些:

truncate("Once upon a time in a world far far away", 14)
# => Once upon a...
truncate("这是一串很长很长的中文字符", 14)
# => 这是一串很长很长的中文...

因为程序截取是按照字符个数来截取,但是中文显示时,一个中文会占据两个英文的宽度。

javaeye有人出了一道Quiz来讨论怎么解决这个问题。

没有评论: