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 Word Count

02.06.2008
| 10310 views |
  • submit to reddit
        
module StringExtensions
  def words
    s = self.dup
    s.gsub!(/\w+/, 'X')
    s.gsub!(/\W+/, '')
    s.length
  end
end
    

Comments

Snippets Manager replied on Fri, 2007/08/17 - 8:08am

And actually, if you want to accept perfectly legitimate words with hyphens, like "one-way street" and "forty-three," you need to go this route: s.scan(/(\w|-)+/).size BTW, Peter, I hadn't happened upon "scan" until reading your book. Thanks!

Snippets Manager replied on Mon, 2012/05/07 - 2:55pm

s.scan(/\w+/).size would probably do the same, btw.