2012-03-17 79 views
1

標題可能會令人困惑。只要說我有一份報紙文章。我希望把它割下圍繞某一點,說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" 

這看起來很容易寫作,但我不知道如何把它變成編程。

回答

5

如何像這樣爲你的例子:

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

1

雖然馬可的答案是普通紅寶石正確的,還有一個更簡單的變體,如果你碰巧使用的軌道,因爲它已經包括truncate helper (這反過來使用由ActiveSupport添加到字符串類truncate method):

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