tags:

views:

237

answers:

3

Say I have a blog model with Title and Body. How I do show the number of words in Body and characters in Title? I want the output to be something like this

Title: Lorem Body: Lorem Lorem Lorem

This post has word count of 3.

+7  A: 
"Lorem Lorem Lorem".scan(/\w+/).size
=> 3

UPDATE: if you need to match rock-and-roll as one word, you could do like

"Lorem Lorem Lorem rock-and-roll".scan(/[\w-]+/).size
=> 4
S.Mark
That's exactly what I was looking for. Thanks.
Senthil
What about "add some rock-n-roll"? There are three words here while your variant will find five.
IDBD
added hyphen too.
S.Mark
+3  A: 

Also:

"Lorem Lorem Lorem".split.size
=> 3
P4010
+2  A: 
"Lorem Lorem Lorem".scan(/\S+/).size
=> 3
IDBD