Word count in Rails?

Viewed 10251

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.

6 Answers
"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

Also:

"Lorem Lorem Lorem".split.size
=> 3
"Lorem Lorem Lorem".scan(/\S+/).size
=> 3
Related