@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"
これはもっと似ています。