Search code examples
rubyword-count

Word count in Rails?


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.


Solution

  • "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