From: Brian Candler Date: 2009-01-16T06:06:57+09:00 Subject: Re: undefined method `[]' for nil:NilClass - how to prevent? Mmcolli00 Mom wrote: > I'll am looking to see if maybe I am missing a gem, not sure. > >>Value does not contain a match: Clashifting.rb:55: undefined method `+' for >nil:NilClass (NoMethodError) .. > counts[word][i] += 1 #line 55 Well, this expression is a shortcut for counts[word][i] = counts[word][i] + 1 so this means that counts[word][i] (on the right hand side) is nil. This will occur if a line of your data file has more than 2 columns. Note that counts['someword'] is initialised to Array(2,0), which is [0,0] so: counts['someword'][0] is 0 counts['someword'][1] is 0 counts['someword'][2] is nil .. same for [3], [4] etc. So it's reading past the end of the array, getting nil, and trying to add 1 to it. The expression nil + 1 is meaningless, of course. The solution depends on what you want to happen when your program reads a line of the form "a,b,c" * Do you want to treat "a" as the first word, and "b,c" as the second? * Do you want to treat "a" and "b" as words, and ignore the rest of the line? Suitable adjustment to the 'split' expression should do the trick. irb(main):001:0> "a,b,c".split(",",2) => ["a", "b,c"] irb(main):002:0> "a,b,c".split(",")[0,2] => ["a", "b"] HTH, Brian. -- Posted via http://www.ruby-forum.com/.