I’ve written a Node class that I’m using to write a few programs for in
a course.
class Node
A node represents a spot on the grid. It knows its
location and parent node, the total cost so far, and
the directions take to get to current location
attr_reader :row, :col, :cost, :direction, :parent, :collected
def initialize(row, col, cost, direction=nil, parent=nil)
@row = row
@col = col
@cost = (parent.nil? ? 0.0 : parent.cost) + cost.to_i
@direction = (parent.nil?) ? “” : parent.direction + direction
@parent = parent
@collected = (parent.nil?) ? [] : parent.collected.to_a
end
def to_s
“row:#{@row} col:#{@col} cost:#{@cost}”
end
def location
[@row, @col]
end
def add_collected
@collected = @collected << [[@row, @col]]
end
end
The problem is with #add_collected. When it is called its updating
@collected for all instances of Node. @collected is suppose to be an
array of arrays. I’m not sure why it’s behaving the way that it is. I’m
still a bit new to ruby. Can anyone give me some insight on why its
behaving the way that it is please. Thanks.