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

问题描述:

标题可能会令人困惑。只要说我有一份报纸文章。我希望把它割下围绕某一点,说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" 
+0

此答案适合我。谢谢您的帮助。 – Eric 2012-03-17 10:37:53

虽然马可的答案是普通红宝石正确的,还有一个更简单的变体,如果你碰巧使用的轨道,因为它已经包括truncate helper (这反过来使用由ActiveSupport添加到字符串类truncate method):

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