"Marcel Molina Jr." <marcel / vernix.org> 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. <marcel / vernix.org>
-- 
Christian Neukirchen  <chneukirchen / gmail.com>  http://chneukirchen.org