DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Ruby: Count Number Of Words In A String

07.18.2007
| 10709 views |
  • submit to reddit
        
class String
  def count_words
    n = 0
    scan(/\b\S+\b/) { n += 1}
    n
  end 
end
    

Comments

replied on Thu, 2007/04/12 - 4:41pm

or you could try class String def count_words split(/\S+/).size end end gotta love ruby and the infinite ways to do things :)