Ruby-on-rails 用 Rails 截断字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7023545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Truncate string with Rails?
提问by krunal shah
I want to truncate a string as follows:
我想截断一个字符串如下:
input:
输入:
string = "abcd asfsa sadfsaf safsdaf aaaaaaaaaa aaaaaaaaaa dddddddddddddd"
output:
输出:
string = "abcd asfsa sadfsaf safsdaf aa...ddddd"
回答by Veger
Take a look at truncate, it partially does want you want. If you test whether it got trunctated or not, you could add some of the last part back after the truncated part.
看看truncate,它确实部分想要你想要的。如果您测试它是否被截断,您可以在截断部分之后添加一些最后一部分。
truncate("Once upon a time in a world far far away")
# => "Once upon a time in a world..."
truncate("Once upon a time in a world far far away", :length => 17)
# => "Once upon a ti..."
truncate("Once upon a time in a world far far away", :length => 17, :separator => ' ')
# => "Once upon a..."
truncate("And they found that many people were sleeping better.", :length => 25, :omission => '... (continued)')
# => "And they f... (continued)"
回答by fl00r
In the simplest case:
在最简单的情况下:
string = "abcd asfsa sadfsaf safsdaf aaaaaaaaaa aaaaaaaaaa dddddddddddddd"
tr_string = string[0, 20] + "..." + string[-5,5]
or
或者
def trancate(string, length = 20)
string.size > length+5 ? [string[0,length],string[-5,5]].join("...") : string
end
# Usage
trancate "abcd asfsa sadfsaf safsdaf aaaaaaaaaa aaaaaaaaaa dddddddddddddd"
#=> "abcd asfsa sadfsaf s...ddddd"
trancate "Hello Beautiful World"
#=> "Hello Beautiful World"
trancate "Hello Beautiful World", 5
#=> "Hello...World"
回答by yegor256
You can do almostthe same without Rails:
如果没有 Rails,你几乎可以做同样的事情:
text.gsub(/^(.{50,}?).*$/m,'...')
50is the length you need.
50是你需要的长度。
回答by Joshua Pinter
Truncate with Custom Omission
使用自定义省略截断
Similar to what some others have suggested here, you can use Rails' #truncatemethod and use a custom omission that is actually the last part of your string:
与其他人在这里建议的类似,您可以使用 Rails 的#truncate方法并使用自定义省略,它实际上是字符串的最后一部分:
string = "abcd asfsa sadfsaf safsdaf aaaaaaaaaa aaaaaaaaaa dddddddddddddd"
truncate(string, length: 37, omission: "...#{string[-5, 5]}")
# => "abcd asfsa sadfsaf safsdaf aa...ddddd"
Exactly what you wanted.
正是你想要的。
Bonus Points
奖励积分
You might want to wrap this up in a custom method called something like truncate_middlethat does some fancy footwork for you:
您可能希望将其包装在一个名为类似的自定义方法中truncate_middle,为您做了一些奇特的步法:
# Truncate the given string but show the last five characters at the end.
#
def truncate_middle( string, options = {} )
options[:omission] = "...#{string[-5, 5]}" # Use last 5 chars of string.
truncate( string, options )
end
And then just call it like so:
然后就这样称呼它:
string = "abcd asfsa sadfsaf safsdaf aaaaaaaaaa aaaaaaaaaa dddddddddddddd"
truncate_middle( string, length: 37 )
# => "abcd asfsa sadfsaf safsdaf aa...ddddd"
Boom!
繁荣!
Thanks for asking about this. I think it's a useful way to show a snippet of a longer piece of text.
感谢您询问此事。我认为这是显示较长文本片段的有用方法。
回答by elliotwesoff
This may not be the exact solution to your problem, but I think it will help put you in the right direction, with a pretty clean way of doing things.
这可能不是您问题的确切解决方案,但我认为它将帮助您朝着正确的方向前进,并以一种非常干净的做事方式。
If you want "Hello, World!" to be limited to the first five letters, you can do:
如果你想要“你好,世界!” 要仅限于前五个字母,您可以这样做:
str = "Hello, World!"
str[0...5] # => "Hello"
If you want an ellipses, just interpolate it:
如果你想要一个椭圆,只需插入它:
"#{str[0...5]}..." #=> "Hello..."
回答by hiveer
This is the source code of String#truncate
这是源代码 String#truncate
def truncate(truncate_at, options = {})
return dup unless length > truncate_at
options[:omission] ||= '...'
length_with_room_for_omission = truncate_at - options[:omission].length
stop = \
if options[:separator]
rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission
else
length_with_room_for_omission
end
"#{self[0...stop]}#{options[:omission]}"
end
So, as for you case
所以,至于你的情况
string.truncate(37, :omission => "...ddddd")
回答by skorks
That's actually an interesting problem and you may want to solve it using javascript rather than ruby. Here is why, you're probably displaying this text on the screen somewhere, and you only have a certain amount of width available. So rather than having your link (or whatever text) cut down to a number of characters, what you really want is to make sure the text you're displaying never exceeds a certain width. How many characters can fit in a certain width depends on the font, spacing etc. (the css styles) you're using. You can make sure everything is ok if you're using a ruby-based solution, but it might all fall appart if you decide to change your styling later on.
这实际上是一个有趣的问题,您可能希望使用 javascript 而不是 ruby 来解决它。这就是为什么,您可能在屏幕上的某处显示此文本,并且您只有一定的宽度可用。因此,与其将您的链接(或任何文本)缩减为多个字符,您真正想要的是确保您显示的文本永远不会超过特定宽度。特定宽度可以容纳多少字符取决于您使用的字体、间距等(css 样式)。如果您使用的是基于 ruby 的解决方案,您可以确保一切正常,但如果您决定稍后更改样式,则可能一切都会分崩离析。
So, I recommend a javascript-based solution. The way I've handled it previously has been to use the jquery truncate plugin. Include the plugin in your app. And then hook in some javascript similar to the following every time the page loads:
所以,我推荐一个基于 javascript 的解决方案。我以前处理它的方式是使用jquery truncate plugin。在您的应用程序中包含该插件。然后在每次页面加载时钩入一些类似于以下内容的 javascript:
function truncateLongText() {
$('.my_style1').truncate({
width: 270,
addtitle: true
});
$('.my_style2').truncate({
width: 100
});
}
Add in whatever other styles need to be truncatable and the width that they should respect, the plugin does the rest. This has the added advantage of having all your truncation logic for the whole app in one place which can be handy.
添加任何其他需要截断的样式和它们应该尊重的宽度,插件会完成剩下的工作。这还有一个额外的好处,就是将整个应用程序的所有截断逻辑都放在一个地方,这很方便。

