0

I'm not sure why this recursive method is returning NoMethodError: undefined method '[]' for nil:NilClass

def test_method(a, b)
    (a[0] == b[0] ? 0 : 1) + test_method(a[1..-1], b[1..-1])
end

edit: I am sending in strings for the arguments to compare them.

2
  • 1
    What arguments are you sending to this method to get that exception? Commented Sep 11, 2012 at 19:15
  • I'm sending in strings to compare them. Commented Sep 11, 2012 at 19:20

3 Answers 3

1

Actually, at one time, it will reduce to empty string and then to nil. And then causes NoMethodError: undefined method '[]' for nil:NilClass.

Something like this is happening:

'ss'[1..-1] => 's'
'ss'[1..-1][1..-1] => ""
'ss'[1..-1][1..-1][1..-1] => nil
Sign up to request clarification or add additional context in comments.

Comments

1

This is because you are not checking whether a and b are empty arrays or not. At one time that will reduce to empty array

before calling you should write

 if not (a.empty? or b.empty?)
  (a[0] == b[0] ? 0 : 1) + test_method(a[1..-1], b[1..-1])
 end

5 Comments

I planned on adding empty string checking later on. Do I need to check it right off the bat? All the tests I have been doing have been with strings longer than 5 characters in length, so I assumed this wouldn't be a problem yet.
but at one time like a[6..-6] will gives back nil. Check this out in console
If it's recursive, at some point you you have to reach the end.
but you have to stop some where explicitly. It will not happen automatically.
Ah, i get it. Can't believe I didn't see it before. Thanks.
1

Since you're iterating over an ever smaller array/string/whatever, you have to account for reaching the end of it. I have no idea what you're trying to accomplish, but this'll at least stop it from blowing up:

def test_method(a, b)
  return 0 if a.nil? || b.nil?
  (a[0] == b[0] ? 0 : 1) + test_method(a[1..-1], b[1..-1])
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.