From: Christian Neukirchen Date: 2006-04-29T23:03:39+09:00 Subject: Re: Counting words "Marcel Molina Jr." writes: > On Sat, Apr 29, 2006 at 02:43:30AM +0900, Jamal Mazrui wrote: >> I've research this but am still having trouble getting it right .... >> Can someone give me code that counts the number of words in a string via >> RegExp and MatchData objects? I think I'd like a word to be defined as >> contiguous characters surrounded by white space (or the start/end of the >> string), though am open to other interpretations. > > Here is a naive implementation: > > class String > def words > scan(/\b\S+\b/) > end > end And quite bit more efficient, memory-wise: class String def count_words n = 0 scan(/\b\S+\b/) { n += 1} n end end Making String#count take regexps would be nice (same for #delete). > Marcel Molina Jr. -- Christian Neukirchen http://chneukirchen.org