2012-06-27 44 views
0

我有以下函數接受文本和字數,如果文本中的字數超過了字數,它會被省略號截斷。紅寶石截斷字+長文本

#Truncate the passed text. Used for headlines and such 
    def snippet(thought, wordcount) 
    thought.split[0..(wordcount-1)].join(" ") + (thought.split.size > wordcount ? "..." : "") 
    end 

但是什麼此功能不會考慮到的是極長的話,比如...

「Helloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo 的世界!」

我想知道是否有更好的方法來處理我正在嘗試做的事情,因此需要以有效的方式考慮字數和文本大小。

+0

使用長詞時,會出現什麼問題? 顯然,它**應**工作,因爲你只是會計字數,而不是他們的長度。 –

回答

4

這是Rails項目?

爲什麼不使用下面的幫助:

truncate("Once upon a time in a world far far away", :length => 17) 

如果沒有,只是重用的代碼。

+2

截斷很好。如果你只是想要truncate方法的代碼,你可以在這裏找到它:https:// github。COM /導軌/導軌/ BLOB/ac4c5e97226fd70510ed49872f0ae41ba0d71c52 /的ActiveSupport/lib中/ active_support/core_ext /串/ filters.rb#L38 – dontangg

1

提示:正則表達式^(\s*.+?\b){5}將匹配前5個 「字」

0

檢查單詞和字符限制的邏輯變得過於複雜,無法清晰地表達爲一個表達式。我建議是這樣的:

def snippet str, max_words, max_chars, omission='...' 
    max_chars = 1+omision.size if max_chars <= omission.size # need at least one char plus ellipses 
    words = str.split 
    omit = words.size > max_words || str.length > max_chars ? omission : '' 
    snip = words[0...max_words].join ' ' 
    snip = snip[0...(max_chars-3)] if snip.length > max_chars 
    snip + omit 
end 

正如其他人指出Rails的字符串#截斷提供了幾乎你想要的(截斷以適應長度在自然邊界)的功能,但它不會讓你獨立狀態最大字符長度和字數。

2

這可能是一個兩個步驟:

  1. 截斷字符串的最大長度(不需要正則表達式這一點)
  2. 使用正則表達式,找到截斷字符串最多的話量。

編輯:

另一種方法是通過在陣列相加 長度分裂串入話,循環。當你發現超限時,join 0 .. index就在溢出之前。

0

前20個字符

>> "hello world this is the world".gsub(/.+/) { |m| m[0..20] + (m.size > 20 ? '...' : '') } 
=> "hello world this is t..." 

第5個字

>> "hello world this is the world".gsub(/.+/) { |m| m.split[0..5].join(' ') + (m.split.size > 5 ? '...' : '') } 
=> "hello world this is the world..."