# Display the first n words from a string

**URL:** <https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832>\
**Category:** Rails\
**Created:** [September 5, 2007, 1:06pm UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832 "2007-09-05T13:06:12Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 5, 2007, 1:06pm UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/1 "2007-09-05T13:06:12Z")

</div>

In my app, a Story has a summary field, and on the page that lists  
stories, i want to show the first ‘n’ (eg twenty) words from the summary  
(which i would follow with “…”).

Does anyone know a simple way to do this? I can think of complicated  
and ugly ways to do it, involving going through the string a char at a  
time counting spaces, but i’m guessing there’s a neat rails helper  
(since there usually is!).

thanks  
max

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 5, 2007, 1:20pm UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/2 "2007-09-05T13:20:15Z")

</div>

Hi Max,

On 5 Sep 2007, at 12:06, Max W. wrote:

> In my app, a Story has a summary field, and on the page that lists  
> stories, i want to show the first ‘n’ (eg twenty) words from the  
> summary  
> (which i would follow with “…”).
> 
> Does anyone know a simple way to do this? I can think of complicated  
> and ugly ways to do it, involving going through the string a char at a  
> time counting spaces, but i’m guessing there’s a neat rails helper  
> (since there usually is!).

I usually go for the roll-your-own method, something like this should  
work nicely for you, just pop the method in your application\_helper  
and call it in your views.

def first\_x\_words(str,n=20,finish=‘…’)  
str.split(’ ')[0,n].inject{|sum,word| sum + ’ ’ + word} + finish  
end

my\_string = ‘Praesent luptatum zzril delenit augue duis dolore te  
feugait nulla facilisi nam! Modo typi qui nunc nobis videntur parum  
clari fiant sollemnes?’

p first\_x\_words(my\_string) # =\> “Praesent luptatum zzril delenit  
augue duis dolore te feugait nulla facilisi nam! Modo typi qui nunc  
nobis videntur parum clari…”

p first\_x\_words(my\_string, 5, ‘!!!’) # =\> “Praesent luptatum zzril  
delenit augue!!!”

Hope this helps.

Douglas F Shearer  
removed\_email\_address@domain.invalid

> **[Douglas F Shearer](https://douglasfshearer.com/)**
>
> Software developer, mountainbiker.

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 5, 2007, 1:30pm UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/3 "2007-09-05T13:30:48Z")

</div>

Douglas S. wrote:

> def first\_x\_words(str,n=20,finish=‘…’)  
> str.split(’ ')[0,n].inject{|sum,word| sum + ’ ’ + word} + finish  
> end

> Hope this helps.
> 
> Douglas F Shearer  
> removed\_email\_address@domain.invalid  
> [http://douglasfshearer.com](http://douglasfshearer.com)

That’s perfect, thanks Douglas.  
(i would never think to use inject as it still confuses me a little!)

cheers  
max

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 5, 2007, 1:38pm UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/4 "2007-09-05T13:38:21Z")

</div>

Max W. wrote:

> Douglas S. wrote:
> 
> > def first\_x\_words(str,n=20,finish=‘…’)  
> > str.split(’ ')[0,n].inject{|sum,word| sum + ’ ’ + word} + finish  
> > end
> 
> > Hope this helps.
> > 
> > Douglas F Shearer  
> > removed\_email\_address@domain.invalid  
> > [http://douglasfshearer.com](http://douglasfshearer.com)
> 
> That’s perfect, thanks Douglas.  
> (i would never think to use inject as it still confuses me a little!)
> 
> cheers  
> max

BTW, i’m just curious - why do you prefer the ellipsis symbol @hellip to  
“…”? Is this a convention?

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 5, 2007, 2:06pm UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/5 "2007-09-05T14:06:35Z")

</div>

On 5 Sep 2007, at 12:56, Peter De Berdt wrote:

> On 05 Sep 2007, at 13:38, Max W. wrote:
> 
> > BTW, i’m just curious - why do you prefer the ellipsis symbol  
> > @hellip to  
> > “…”? Is this a convention?
> 
> … renders correctly across all browsers, even if they don’t  
> respect the utf-8 encoding defined in the header.

Peter hit that nail on the head. It also looks a bit neater as the  
letter-spacing is smaller between the periods of &hellip.

Glad it helped you out.

Douglas F Shearer  
removed\_email\_address@domain.invalid

> **[Douglas F Shearer](https://douglasfshearer.com/)**
>
> Software developer, mountainbiker.

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 5, 2007, 1:57pm UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/6 "2007-09-05T13:57:33Z")

</div>

On 05 Sep 2007, at 13:38, Max W. wrote:

> BTW, i’m just curious - why do you prefer the ellipsis symbol  
> @hellip to  
> “…”? Is this a convention?

… renders correctly across all browsers, even if they don’t  
respect the utf-8 encoding defined in the header.

Best regards

Peter De Berdt

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 5, 2007, 5:34pm UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/7 "2007-09-05T17:34:18Z")

</div>

First of all, split takes a limiter, and its inverse is join:  
words = str.split(’ ‘, n + 1)  
words[-1] = finish  
words.join(’ ')

But is this really what you want? Suppose the book was a discussion  
on Mary Poppins? It seems to me that you have space for n characters,  
and you need to end at a word break:  
letters = str[0…limit - finish.length]  
letters.sub!(/ \S\*$/)  
letters + " " + finish

On Sep 5, 7:08 am, Max W. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 5, 2007, 2:08pm UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/8 "2007-09-05T14:08:26Z")

</div>

Douglas S. wrote:

> > … renders correctly across all browsers, even if they don’t  
> > respect the utf-8 encoding defined in the header.
> 
> Peter hit that nail on the head. It also looks a bit neater as the  
> letter-spacing is smaller between the periods of &hellip.

ahhh. nice tip, thanks guys.

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 5, 2007, 7:42pm UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/9 "2007-09-05T19:42:48Z")

</div>

> > def first\_x\_words(str,n=20,finish=’…’)  
> > str.split(’ ')[0,n].inject{|sum,word| sum + ’ ’ + word} + finish  
> > end

> That’s perfect, thanks Douglas.  
> (i would never think to use inject as it still confuses me a little!)

No need for inject–you can rewrite that line:  
str.split(’ ‘)[0,n].join(’ ') + finish

If, like another poster said, it is a CHARACTER limitation, yet you  
still want to break on a word boundary, then replace the line with:  
str[0,n].sub(/ ?\S\*$/,’’) + finish

- Mark.

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 5, 2007, 5:58pm UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/10 "2007-09-05T17:58:43Z")

</div>

Student wrote:

> First of all, split takes a limiter, and its inverse is join:  
> words = str.split(’ ‘, n + 1)  
> words[-1] = finish  
> words.join(’ ')
> 
> But is this really what you want? Suppose the book was a discussion  
> on Mary Poppins? It seems to me that you have space for n characters,  
> and you need to end at a word break:  
> letters = str[0…limit - finish.length]  
> letters.sub!(/ \S\*$/)  
> letters + " " + finish
> 
> On Sep 5, 7:08 am, Max W. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)

Your suggestion is actually closer to what i want - thanks! However,  
i’m having problems with the regular expression is sub - shouldn’t sub  
take two parameters? What exactly is this line meant to be doing?

I put the above into a helper method, and when i call it i get a strange  
error:  
“wrong number of arguments (1 for 2)”

I’m definitely calling it correctly, and when i take the .sub line out  
then it works (except for completing the last word, obviously).

Would you mind explaining this a bit?

thanks a lot  
max

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 6, 2007, 12:04am UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/11 "2007-09-06T00:04:28Z")

</div>

Max W. wrote:

> In my app, a Story has a summary field, and on the page that lists  
> stories, i want to show the first ‘n’ (eg twenty) words from the summary  
> (which i would follow with “…”).
> 
> Does anyone know a simple way to do this? I can think of complicated  
> and ugly ways to do it, involving going through the string a char at a  
> time counting spaces, but i’m guessing there’s a neat rails helper  
> (since there usually is!).
> 
> thanks  
> max

Hey Max,  
do you not just want the truncate rails helper?

> **[ActionView::Helpers::TextHelper](https://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M000615)**
>
> The TextHelper module provides a set of methods for filtering, formatting and transforming strings, which can reduce the amount of inline Ruby code in your views.

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 6, 2007, 4:33am UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/12 "2007-09-06T04:33:45Z")

</div>

On Sep 5, 6:04 pm, Matthew R. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> Hey Max,  
> do you not just want the truncate rails helper?
> 
> [ActionView::Helpers::TextHelper](http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html)…

No, because he wants to break only on word boundaries.

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 6, 2007, 7:19am UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/13 "2007-09-06T07:19:57Z")

</div>

On Sep 5, 2007, at 8:58 AM, Max W. wrote:

> > and you need to end at a word break:
> 
> I put the above into a helper method, and when i call it i get a  
> strange  
> error:  
> “wrong number of arguments (1 for 2)”
> 
> I’m definitely calling it correctly, and when i take the .sub line out  
> then it works (except for completing the last word, obviously).
> 
> Would you mind explaining this a bit?

Check out this helper: [http://pastie.textmate.org/94218](http://pastie.textmate.org/94218)

–  
Benjamin C.  
[http://www.bencurtis.com/](http://www.bencurtis.com/) – blog  
[http://agilewebdevelopment.com/guides](http://agilewebdevelopment.com/guides) – Rails tutorials

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 6, 2007, 8:02am UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/14 "2007-09-06T08:02:59Z")

</div>

Basically the same thing aside from the encapsulation in a class.  
Didn’t see that one when I wrote mine. I went ahead and pluginized  
mine, though, since I’ll probaby use it often:

svn://reinh.com/plugins/truncator

truncate, truncate\_words, truncate\_sentences, truncate\_on

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 6, 2007, 8:04am UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/15 "2007-09-06T08:04:59Z")

</div>

Oh, I forgot to mention, it also removes trailing punctuation from the  
truncated string to avoid typographical errors like: “Lorem ipsum,…”

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 6, 2007, 5:37am UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/16 "2007-09-06T05:37:50Z")

</div>

inject here is unnecessarily expensive. I try to avoid using inject if  
it isn’t really needed.

Using ActionView’s truncate() as a model:

def truncate\_words(text, num\_words = 6, truncate\_string = “…”)  
if text.nil? then return end  
arr = text.split(’ ‘)  
arr.length \> num\_words ? arr[0…num\_words].join(’ ') +  
truncate\_string : text  
end

ReinH  
[reinh.com](http://reinh.com)

On Sep 5, 6:30 am, Max W. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 6, 2007, 11:31am UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/17 "2007-09-06T11:31:24Z")

</div>

Please unsubscribe me from this google group

Thanks

Joseph Chapman,

* * *

Get free emoticon packs and customisation from Windows Live.  
[http://www.pimpmylive.co.uk](http://www.pimpmylive.co.uk)

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 6, 2007, 12:07pm UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/18 "2007-09-06T12:07:15Z")

</div>

Mohit S. wrote:

> Joseph:  
> To unsubscribe from this group, send email to  
> removed\_email\_address@domain.invalid
> 
> Bye!  
> Mohit.

he’s a spammer, ignore him 🙂

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 6, 2007, 3:38pm UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/19 "2007-09-06T15:38:05Z")

</div>

Changing the subject back to something useful.

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [September 6, 2007, 12:02pm UTC](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832/20 "2007-09-06T12:02:28Z")

</div>

Joseph:  
To unsubscribe from this group, send email to  
removed\_email\_address@domain.invalid

Bye!  
Mohit.

[Next page](https://www.ruby-forum.com/t/display-the-first-n-words-from-a-string/113832.md?page=2)
