Truncate string to the first n words

前端 未结 4 1684
有刺的猬
有刺的猬 2020-12-28 14:16

What\'s the best way to truncate a string to the first n words?

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-28 15:07

    You could do it like this:

    s     = "what's the best way to truncate a ruby string to the first n words?"
    n     = 6
    trunc = s[/(\S+\s+){#{n}}/].strip
    

    if you don't mind making a copy.

    You could also apply Sawa's Improvement (wish I was still a mathematician, that would be a great name for a theorem) by adjusting the whitespace detection:

    trunc = s[/(\s*\S+){#{n}}/]
    

    If you have to deal with an n that is greater than the number of words in s then you could use this variant:

    s[/(\S+(\s+)?){,#{n}}/].strip
    

提交回复
热议问题