2012-11-28 16 views
1

我們有一個句子和一個字符限制。如果超過了字符數限制,我們想截斷這個句子,但是隻能在一個空格處,而不是在一個字的中間。如何在最近的空間截斷句子?

這是我們到目前爲止有:

def shortened_headline(max_length) 
    return @headline unless @headline.length > max_length 
    @headline[0..max_length] 
    end 

回答

3

已經修剪您可以使用rindex從數組或字符串右邊找東西的索引標題。

喜歡的東西:

[email protected][0..max_length].rindex(' ') 

會給你在標題中最後一個空格的位置。如果您想在字符串中找到最後一個非字母數字字符,那麼您也可以將其與正則表達式一起使用,以便可以打破最後一個空格或標點符號。

More on rindex here.

2

您應該使用String#index。它找到字符串第一次出現的索引,並且它也接受和偏移。

注:此實現削減在第一空間字符串的MAX_LENGTH後(其中,我才意識到,可能不是你想要的)。如果您需要在max_length之前切割第一個空格,請參閱@ glenatron的答案。

def shortened_headline(headline, max_length) 
    return headline if headline.length < max_length 

    space_pos = headline.index(' ', max_length) 
    headline[0..space_pos-1] 
end 

h = 'How do you truncate a sentence at the nearest space?' 

h[0..4] # => "How d" 
shortened_headline(h, 5) # => "How do" 

h[0..10] # => "How do you " 
shortened_headline(h, 10) # => "How do you" 

h[0..15] # => "How do you trunc" 
shortened_headline(h, 15) # => "How do you truncate" 
3

導軌具有多種便捷的方法,其中一個truncate方法,你可以通過一個:separator選件擴展了String類。即使你不使用Rails,你也可以簡單地複製它們的實現。查看文檔在

http://api.rubyonrails.org/classes/String.html#method-i-truncate

(你可以點擊「顯示源代碼」來查看實際implemetation)

+0

這就是爲什麼Rails太棒了。這就像他們實際上已經想到_everything_。 – glenatron

0
@headline[/.{,#{max_length}}(?: |\z)/] 
1

看看的ActiveSupport的核心,擴展爲字符串,特別是truncate方法。

從文檔:

The method truncate returns a copy of its receiver truncated after a given length: 

    "Oh dear! Oh dear! I shall be late!".truncate(20) 
    # => "Oh dear! Oh dear!..." 

訪問這樣的:

irb(main):001:0> require 'active_support/core_ext/string/filters' 
irb(main):002:0> 'how now brown cow'.truncate(10) 
=> "how now..." 

truncate方法來關閉省略號如果你不想額外裝飾的能力。

ActiveSupport重構了一段時間,讓我們能夠選擇我們想要的功能,而無需拉入整個庫。它充滿善良。 core-extension page有更多的信息。