2009-04-03 2 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

Railsアプリケーションでは、基本的なStringクラスを拡張する( "monkey patch")という非常によく似たものを使用しています。

私は含まれ​​を作成しました:

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

を私は、含まれているconfig/initializers/load_extensions.rbを作成しました:

require 'core_extensions' 

を今、私はRailsアプリケーション内のすべての私のStringオブジェクトのto_blurb()メソッドを持っています。

関連する問題