From: Robert Klemme Date: 2009-01-15T16:04:12+09:00 Subject: Re: undefined method `[]' for nil:NilClass - how to prevent? On 15.01.2009 05:51, Mmcolli00 Mom wrote: > This returns correct value so long as I do not use array[0][i]. The > error is: > >> searchArray.rb:13: undefined method `[]' for nil:NilClass (NoMethodError) >> from shifting1.rb:7:in `each_line' >> from shifting1.rb:7 >> Exit code: 1 >> > #************************************** > #Searches through a text file and, at one row at a time, counts how many > occurrences of the value exist for the column. For instance, if word, > 'bird' exists in column1 row1 then count how many birds exist for the > whole column. Next..count the occurrences of bird in the column 2. If > the numbers do not match then outputs "Value does not contain a match:" > +Value. > > I am having this issue with NilClass a lot this week. What do you think > I should change? The whole piece of code. No seriously, there are quite a few things to say: > ##start code > > col1 = 0 > col2 = 0 > > File.open('temp.txt', 'r+').each_line do |temp| The file handle is not closed properly. Rather use the block form of File.open. Also, since you do not write the file, you can as well use File.foreach 'temp.txt' do |temp| ... end Btw, the name "temp" doesn't tell much about the contents of the variable. I'd pick another, more meaningful name like "line". > array = [] Superfluous initialization... > i = 0 > array = temp.chomp.split(",",0) ... because here you overwrite "array" immediately without reading it. > arrayVal1 = array[0][i] > arrayVal2 = array[1][i] > > if array[0] == arrayVal1 then As far as I can see this does not make sense: the comparison can never be "true" because you compare an object (array[0]) with part of it (array[0][i]). > col1 = col1 + 1 > end > > if array[1] == arrayVal2 then > col2 = col2 + 1 > end > i = i + 1 > > if col1 != col2 then > puts "Value does not contain a match:" > puts arrayVal1 > end I have no idea what this is supposed to do: you compare global counts of matches for every line. But: if there once was a mismatch in a line, counts will not be the same in the next matching line. Is this really what you want? Your description does not make this clear. > end > > ##end code > > Attachments: > http://www.ruby-forum.com/attachment/3164/searchArray.rb The whole bit certainly does not match your description. How about: counts = values = nil File.foreach 'temp.txt' do |line| line.chomp! # better use CSV parsing: fields = line.split ',' if values fields.each_with_index |f,i| counts[i] += 1 if values[i] == f end else # init search strings values = fields counts = Array.new(values.size, 0) end end Cheers robert -- remember.guy do |as, often| as.you_can - without end