e_r*_*e_r 33 ruby string ruby-on-rails-4
我试图将一长串文本截断到一定长度,但也希望确保截断的结果在空格处结束.之后我还要附加一个省略号.
例如:
"This is a very long string that has more characters than I want in it."
Run Code Online (Sandbox Code Playgroud)
成为这个:
"This is a very long string that..."
Run Code Online (Sandbox Code Playgroud)
我从这开始,但显然这不涉及在空格上结束字符串的问题.
<%= item.description[0..30] %>…
Run Code Online (Sandbox Code Playgroud)
Jor*_*ing 42
如果你使用的是Rails 4+,你应该使用内置的truncate帮助方法,例如:
<%= truncate item.description, length: 30, separator: /\w+/ %>
Run Code Online (Sandbox Code Playgroud)
字符串"..."将附加到截断的文本; 要指定不同的字符串,请使用:omission选项,例如omission: "xxx".
对于Rails 3.x,:separator选项必须是字符串.:separator => " "在许多情况下,给予会很好,但只能抓住空间而不是其他空白.一个折衷方案是使用String#squish,它用一个空格替换所有空白序列(并且还修剪前导和尾随空格),例如"foo\n\tbar ".squish产量"foo bar".它看起来像这样:
<%= truncate item.description.squish, :length => 30, :separator => /\w/,
:omission => "…" %>
Run Code Online (Sandbox Code Playgroud)
evf*_*qcg 41
s[0..30].gsub(/\s\w+\s*$/, '...')
Run Code Online (Sandbox Code Playgroud)
原始答案在30个字符子串以空白字符结束的情况下不起作用.这解决了这个问题.
>> desc="This is some text it is really long"
>> desc[0..30].gsub(/\s\w+$/,'...')
"This is some text it is really "
>> desc[0..30].gsub(/\s\w+\s*$/,'...')
"This is some text it is..."
Run Code Online (Sandbox Code Playgroud)
@ 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..."
Run Code Online (Sandbox Code Playgroud)
这不是我的预期.
这是我用来解决这个问题的方法:
def truncate s, length = 30, ellipsis = '...'
if s.length > length
s.to_s[0..length].gsub(/[^\w]\w+\s*$/, ellipsis)
else
s
end
end
Run Code Online (Sandbox Code Playgroud)
在做测试时,输出如下:
>> 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..."
Run Code Online (Sandbox Code Playgroud)
仍然按预期行事.
>> 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"
Run Code Online (Sandbox Code Playgroud)
这是更喜欢它.
| 归档时间: |
|
| 查看次数: |
33107 次 |
| 最近记录: |