In the following code I have two classes. When the Nation class is instantiated to an object, it also instantiates an object for the Population class with a reference to the nation object.
class Nation
def initialize(name)
@name = name
@population = Population.new(self)
end
end
class Population
def initialize(nation)
@nation = nation
end
end
pry(main)> n = Nation.new("Germany")
=> #<Nation:0x0000000b3179e0 @name="Germany", @population=#<Population:0x0000000b3179b8 @nation=#<Nation:0x0000000b3179e0 ...>>>
Is this the case of circular reference?
Is it something that should be avoided?
Why is the Ruby interpreter not giving any errors? Isn't this leading to a kind of infinite recursion? When I create object n, it comes with a reference to object p, which comes with a reference to object n, which comes with a reference to object p... so how is the interpreter not going is some kind of infinite loop, as when you have a recursive function, which eventually terminates with a stack too deep error?
How could I refactor code like this where objects need to know about each others?