From: Robert Klemme Date: 2010-05-20T16:58:18+09:00 Subject: Re: method returning a hash, is the hash in the heap? 2010/5/20 Jian Lin : > For this program: > > class Point >  def initialize(x,y) >    @x,@y = x,y >    @something = 123.456 >  end > >  def instance_variables_and_values >    hash = {} >    instance_variables.each {|n| hash[n] = instance_variable_get(n)} >    return hash >  end > > end > > p1 = Point.new(1,2) > p p1.instance_variables_and_values > > p2 = Point.new(3,4) > p p1.instance_variables_and_values > p p2.instance_variables_and_values > > so the hash is actually allocated in the Heap, and the local variable in > the Stack is just the "hash" reference? It is just _a_ reference - there can be multiple references to an instance and none of them is special. > So when the method returns, the "hash" variable, which is just a > reference to the hash object, is destroyed.  But the hash object that is > in the Heap will stay as long as there is a reference to it (a reference > from outside)? Yep, basically that's it. I would pick a tad different wording but you have grokked the essence of it. With references we usually do not speak of "destruction" because that is something typically done to objects. References are simply forgotten or lost, I would say. The lifetime of an instance is more accurately described as "from its creation until GC decides to remove it". Of course, the earliest point in time when GC can decide to remove it is after the last reference to the instance has gone. (Note there is a special case with WeakReference but I don't want to complicate things too much initially. There are also ways to access an instance during the period between "last ref gone" and "GC removed it" via ObjectSpace but this is not something you should rely on.) Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/