Never been to DZone Snippets before?

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

Ruby word count (See related posts)

module StringExtensions
  def words
    s = self.dup
    s.gsub!(/\w+/, 'X')
    s.gsub!(/\W+/, '')
    s.length
  end
end

Comments on this post

peter posts on Feb 06, 2008 at 22:51
s.scan(/\w+/).size would probably do the same, btw.
bjhess posts on Feb 28, 2008 at 22:03
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!

You need to create an account or log in to post comments to this site.


Click here to browse all 4852 code snippets

Related Posts