繁体   English   中英

如何从字符串的开头到在Ruby中的字符串中的特定索引之前的字符的最后一次出现取子字符串

[英]How to take a substring from the beginning of a string up to the last occurrence of a character that is before a specific index in the string in Ruby

标题可能会造成混淆。 只是说我有一篇报纸文章。 我想在某个点(例如4096个字符)处将其剪掉,但不要在一个单词的中间,而不是在长度超过4096的最后一个单词之前。这是一个简短的示例:

"This is the entire article."

如果要在总长度超过16个字符的单词之前将其剪掉,这是我想要的结果:

"This is the entire article.".function
=> "This is the"

“整个”一词的总长度超过16个,因此必须连同其后的所有字符以及其前面的空格一起删除。

这是我不想要的:

"This is the entire article."[0,15]
=> "This is the ent"

它看起来很容易编写,但是我不知道如何将其用于编程。

对于您的示例,这样的事情怎么样:

sentence = "This is the entire article."
length_limit = 16
last_space = sentence.rindex(' ', length_limit) # => 11
shortened_sentence = sentence[0...last_space]   # => "This is the"

尽管marco的答案对于普通的红宝石是正确的,但是如果您碰巧使用rails,则有一个更简单的变体,因为它已经包含了truncate helper (反过来,它使用ActiveSupport添加到String类的truncate方法 ):

text = "This is the entire article."
truncate(text, :length => 16, :separator => ' ')
# or equivalently
text.truncate(16, :separator => ' ')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM