>I tried the following, but I can't believe that the sample script >could be wrong, anyone want to explain to me what's going on?: > >C:\ruby\sample>ruby occur.rb occur.rb >occur.rb:7: undefined method `+' for nil (NameError) > from occur.rb:6:in `each' > from occur.rb:6 >------------------------------------------------------------------- >occur.rb is very short: >-------------------------------------- ># word occurrence listing ># usege: ruby occur.rb file.. >#freq = {} >freq = Hash.new(0) >while gets() > for word in $_.split(/\W+/) > freq[word] +=1 > end >end > >for word in freq.keys.sort > printf("%s -- %d\n", word, freq[word]) >end > >--------------------------------------------------- > The error is is in "freq[word] +=1". You try to increment a value, which doesn't exits or is nil. This only happens if the key <word> isn't in the hash table. Try the method <fetch> in class <Hash> which results a default value if the key is not available or is nil. The working program: freq = Hash.new(0) while gets() != "\n" for word in $_.split(/\W+/) freq[word] = freq.fetch(word,0) + 1 end end for word in freq.keys.sort printf("%s -- %d\n", word, freq[word]) end Michael