From: Axel Etzold Date: 2009-01-15T18:36:11+09:00 Subject: Re: undefined method `[]' for nil:NilClass - how to prevent? -------- Original-Nachricht -------- > Datum: Thu, 15 Jan 2009 13:51:06 +0900 > Von: Mmcolli00 Mom > An: ruby-talk@ruby-lang.org > Betreff: undefined method `[]\' for nil:NilClass - how to prevent? > 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? > > ##start code > > col1 = 0 > col2 = 0 > > File.open('temp.txt', 'r+').each_line do |temp| > array = [] > i = 0 > array = temp.chomp.split(",",0) > > arrayVal1 = array[0][i] > arrayVal2 = array[1][i] > > if array[0] == arrayVal1 then > 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 > > end > > ##end code > > Attachments: > http://www.ruby-forum.com/attachment/3164/searchArray.rb > > -- > Posted via http://www.ruby-forum.com/. Hi --- in some lines of your data, the split function doesn't find the appropriate pattern, so you have array==[], and thus, there isn't any array[0], i.e. array[0]==nil, and for nil, which is NilClass rather than Array, there are no elements defined. An alternative would be to do something like this: begin arrayVal1 = array[0][i] rescue arrayVal1=["something_else_you'll_have_to_fill_in"] end begin arrayVal2 = array[0][i] rescue arrayVal2=["still_something_else_you'll_have_to_fill_in"] end which will try to execute the first statement after "begin", and if that fails, the statement after "rescue". A conceptually cleaner way yet would be to assign a default value to the array variable, array=Array.new(['nothing in here']) Best regards, Axel -- Psssst! Schon vom neuen GMX MultiMessenger geh�rt? Der kann`s mit allen: http://www.gmx.net/de/go/multimessenger