@evfwcqcg 的回答非常好。我发现它没有很好地工作时
- 该字符串包含其他非空格非字母数字字符。
- 字符串比所需长度短。
示范:
>> s = "How about we put some ruby method Class#Method in our string"
=> "How about we put some ruby method Class#Method in our string"
>> s[0..41].gsub(/\s\w+\s*$/, '...')
=> "How about we put some ruby method Class#Me"
>> s[0..999].gsub(/\s\w+\s*$/, '...')
=> "How about we put some ruby method Class#Method in our..."
这不是我所期望的。
这是我用来解决此问题的方法:
def truncate s, length = 30, ellipsis = '...'
if s.length > length
s.to_s[0..length].gsub(/[^\w]\w+\s*$/, ellipsis)
else
s
end
end
进行测试时,输出如下:
>> s = "This is some text it is really long"
=> "This is some text it is really long"
>> truncate s
=> "This is some text it is..."
仍然按预期行事。
>> s = "How about we put some ruby method Class#Method in our string"
=> "How about we put some ruby method Class#Method in our string"
>> truncate s, 41
=> "How about we put some ruby method Class..."
>> truncate s, 999
=> "How about we put some ruby method Class#Method in our string"
这是更喜欢它。