namtax
namtax

Reputation: 2467

Adding object to array of arrays

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

Upvotes: 0

Views: 156

Answers (1)

Pedro Cori
Pedro Cori

Reputation: 2066

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

Upvotes: 1

Related Questions