2009-04-03 3 views

답변

4

Aaron Hinni's answer과 동일하지만,

def truncate(text, max_sentences = 3, max_words = 50) 
    # Take first 3 setences (blah. blah. blah) 
    three_sentences = text.split('. ').slice(0, max_sentences).join('. ') 
    # Take first 50 words of the above 
    shortened = three_sentences.split(' ').slice(0, max_words).join(' ') 
    return shortened # bah, explicit return is evil 
end 

또한이 책은 어떤이있는 경우, (이 문장이 너무 오래했다 있다면, 50 개 단어로 절단 후) 시도 3 개 완전 문장을 유지합니다 HTML, 내 대답은 "Truncate Markdown?" 일 수 있습니다

+0

나는 이것에 +1을주고, 좋은 생각은 ;-) –

6

단어가 공백으로 구분되어 있다고 가정하면 다음과 같이 할 수 있습니다. 대부분

stories.split(' ').slice(0,50).join(' ') 
0

레일 응용 프로그램에서 뭔가를 사용하여 매우 비슷한 ("원숭이 패치") 기본 String 클래스를 확장합니다.

require 'core_extensions' 

지금 내가 레일 응용 프로그램 내 모든 String 객체에 to_blurb() 방법이 있습니다

class String 
    def to_blurb(word_count = 30) 
    self.split(" ").slice(0, word_count).join(" ") 
    end 
end 

내가 다음이 포함 된 config/initializers/load_extensions.rb을 만들어 :

나는 포함 lib/core_extensions.rb를 만들었습니다.

관련 문제