0

I am trying to add an object to an array of arrays, but when i do, i am recieving an error in my array of array unit tests, stating :- "undefined method 'has_key' for nil:NilClass". However, if i try and add a string or number to the array of array, it works absolutely fine.

I set up my array of arrays like this

@array_of_array= Array.new(5) { Array.new(3) }

Now if I try to do this

@array_of_array[0][0] = MyObject.new

Then if I run my unit tests against @array_of_array, i get the error.

But if I try to do this

@array_of_array[0][0] = 'Test'

Theres no problem.

--Edited---

Heres failing test

it "should place object in correct starting position" do
array_of_array= Array.new(5) { Array.new(3) }
array_of_array[1][0] = MyObject.new
array_of_array.should eql('fail on purpose..want to see output')

end

Im new to ruby, so unsure of where im going wrong. Thanks

6
  • 2
    Could you please provide the code of the failing test? Commented Oct 21, 2011 at 16:44
  • 2
    Works for me. has_key is a method called on a Hash, not an Array, so can you paste the stack trace? Commented Oct 21, 2011 at 16:46
  • 1
    does a = MyObject.new work? Commented Oct 21, 2011 at 17:03
  • no a = myObject.new fails as well Commented Oct 21, 2011 at 17:32
  • 1
    @namtax: That would indicate that the problem lies with MyObject.new rather than with the array. Commented Oct 21, 2011 at 18:00

1 Answer 1

1

Like Claw said, the error probably means that your MyObject.new statement is returning a nil object for some reason. Then you're trying to call the function 'has_key' of that nil object.

Does your MyObject class throw an exception if you use .new! instead of .new ? If so, you could see why it's failing to return a proper MyObject object.

Edit

To catch an exception inside your 'new' method for the MyObject model, you could do something like:

def new
    begin
        #whatever is done in this method
    rescue => exception
        puts exception.message
    end
end
Sign up to request clarification or add additional context in comments.

4 Comments

Ok, when i try MyObject.new! I get :- NoMethodError: undefined method 'new!' for MyObject
Yeah. So there is no exception throwing .new method for your MyObject class. You could put a begin rescue statement inside the 'new' function in the model and see if it throws an exception (Look at edit in answer).
Hi Vota I actually abandoned my approach of storing the object in the array, so didnt get opportunity to try your solution. Its true that the error was occurring because the new statement was returning a nil object.
@namtax No worries. Glad I could be of some help :)

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.