Word count in Rails?

sent-hil picture sent-hil · Jan 21, 2010 · Viewed 9.7k times · Source

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.

Answer

YOU picture YOU · Jan 21, 2010
"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