想要在ruby中显示文本字段的前50或60个单词吗?

Arc*_*Arc 3 ruby ruby-on-rails

我有一个故事文本字段,并希望在快照页面中显示前几行 - 比如该字段的前50个单词.我怎么能在Ruby(在Rails上)做到这一点?

Aar*_*nni 6

假设你的单词是由空格分隔的,你可以做这样的事情.

stories.split(' ').slice(0,50).join(' ')
Run Code Online (Sandbox Code Playgroud)


dbr*_*dbr 5

Aaron Hinni 的回答大致相同,但会尝试保留 3 个完整的句子(然后截断为 50 个单词,如果句子太长)

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
Run Code Online (Sandbox Code Playgroud)

另外,如果此文本有任何 HTML,我的回答是“截断 Markdown?” 可能有用