在Ruby中,如何从字符串的开头提取子字符串,直到字符串中特定索引之前的字符的最后一次出现
标题可能会令人困惑。就说我有一篇报纸文章。我想把它切掉某个点,比如说4096个字符,但不是在一个词的中间,而是在最后一个字的长度超过4096个字之前。下面是一个简短的例子:在Ruby中,如何从字符串的开头提取子字符串,直到字符串中特定索引之前的字符的最后一次出现,ruby,string,substring,Ruby,String,Substring,标题可能会令人困惑。就说我有一篇报纸文章。我想把它切掉某个点,比如说4096个字符,但不是在一个词的中间,而是在最后一个字的长度超过4096个字之前。下面是一个简短的例子: "This is the entire article." 如果我想在一个总长度超过16个字符的单词之前将其截断,我希望得到以下结果: "This is the entire article.".function => "This is the" 单词“整”的总长度超过16,因此必须删除它,以及它后面的所有字符和它
"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"
你的例子是这样的:
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的答案对于普通ruby是正确的,但如果您碰巧使用rails,则有一个更简单的变体,因为它已经包含了一个函数,而该函数又使用了ActiveSupport添加到String类中的:
text = "This is the entire article."
truncate(text, :length => 16, :separator => ' ')
# or equivalently
text.truncate(16, :separator => ' ')
虽然marco的答案对于普通ruby是正确的,但如果您碰巧使用rails,则有一个更简单的变体,因为它已经包含了一个函数,而该函数又使用了ActiveSupport添加到String类中的:
text = "This is the entire article."
truncate(text, :length => 16, :separator => ' ')
# or equivalently
text.truncate(16, :separator => ' ')