Bird
Bird

Reputation: 580

Ruby | Change variable reference to nil

I have the following scenario:

# Keeps track of all `HomeMadeObject` objects
obj_list = []

# A 2-dimensional matrix of either `nil` or `HomeMadeObject` elements
matrix = ...

# I then add an object like so.
obj = HomeMadeObject.new
matrix[y][x] = obj
obj_list.push(obj)

# Later on, I need to remove 'that same object' from the `matrix`.
matrix[y][x] = nil

When I set matrix[y][x] to nil, this will also affect the same object in the obj_list, making it also nil in the obj_list.

puts obj_list[0] # nil

What I'd like to do is to change the matrix[y][x] pointer's location (or the reference) so that the matrix[y][x] points to the nil object. In that way, obj_list points to all the correct objects and the matrix cells can address different locations without overriding a HomeMadeObject object by nil (creating nil elements in obj_list).

Edit

I would like to update the objects in obj_list and see the updates in the matrix (so I need to have some kind of a reference here to the original object). But When a HomeMadeObject isn't needed anymore in the matrix, I want to remove it only from the matrix.

Upvotes: 0

Views: 123

Answers (1)

Rajagopalan
Rajagopalan

Reputation: 6064

All you have to understand here is, In Ruby all variables and constants store references to objects. That’s why one can’t copy the content by assigning one variable to another variable. Variables of type Object in Java or pointers to objects in C++ are good to think of. However, you can’t change the value of each pointer itself.

So use dup method when you are pushing into the object list, your problem is solved.

obj_list.push(obj.dup)

Upvotes: 1

Related Questions