Johannes Friestad
12/14/2005 4:58:00 AM
The simplest way to debug something like this is to add a few print
statements so you see which values are involved.
The error
>> /creat.rb:25:in `blkcheck': undefined method `[]' for nil:NilClass
> > (NoMethodError)
means that your line 25 has just called '[]' on nil.
So in line 25
>> 3.times { |l| tmp <<= tab[i+k+l][j+k] }
either "tab" or "tab[i+k+l]" is nil. But you don't know which, or why.
By adding a couple of print statements to your method, like this
--------
def blkcheck (tab, i, j)
tmp = []
printf("input: i=%i, j=%i, tab(length=%i)=%s\n", i, j, tab.length,
tab.inspect)
3.times do |k|
3.times { |l|
e1=tab[i+k+l]
e2=e1[j+k] if e1
printf("tab[%i]=%s, tab[%i][%i]=%s\n", i+k+l, e1.inspect,
i+k+l, j+k, e2.inspect)
tmp <<= tab[i+k+l][j+k]
}
end
1 if tmp.sort == Val
end
--------
you'll get a printout like this
------
input: i=6, j=0, tab(length=9)=[[1, 2, 3, ...]....]
tab[6]=[1, 2, 3, 4, 5, 6, 7, 8, 9], tab[6][0]=1
tab[7]=[1, 2, 3, 4, 5, 6, 7, 8, 9], tab[7][0]=1
tab[8]=[1, 2, 3, 4, 5, 6, 7, 8, 9], tab[8][0]=1
tab[7]=[1, 2, 3, 4, 5, 6, 7, 8, 9], tab[7][1]=2
tab[8]=[1, 2, 3, 4, 5, 6, 7, 8, 9], tab[8][1]=2
tab[9]=nil, tab[9][1]=nil
NoMethodError: undefined method `[]' for nil:NilClass
-----
and it's easy to see that the nil error comes from calling tab[9] on
an array of length 9.
Good luck with your future debugging :)
On 12/13/05, dblack@wobblini.net <dblack@wobblini.net> wrote:
> Hi --
>
> On Wed, 14 Dec 2005, Mark Liang wrote:
>
> > I've recently started learning Ruby, I cannot seem to locate the
> > cause of this error. Please pardon me if the answer is more
> > straightforward as it seems.
> >
> > ../creat.rb:25:in `blkcheck': undefined method `[]' for nil:NilClass
> > (NoMethodError)
> > from ./creat.rb:25:in `times'
> > from ./creat.rb:25:in `blkcheck'
> > from ./creat.rb:24:in `times'
> > from ./creat.rb:24:in `blkcheck'
> > from ./creat.rb:33:in `blkscheck'
> > from ./creat.rb:32:in `each'
> > from ./creat.rb:32:in `blkscheck'
> > from ./creat.rb:45
> >