Need help to pick up the live objects while using ObjectSpace#each_object

I wrote the code below :

class Animal
  attr_reader :number

  def initialize(name, number)
    @name = name
    @number = number
  end

  def self.all_numbers
    ObjectSpace.each_object(self).map(&:number)
  end
end

an1 = Animal.new('Dog', 23)
an2 = Animal.new('Tiger', 18)

Animal.all_numbers
# => [18, 23]

Somewhere I read that `ObjectSpace#each_object` can pick up objects that
are abandoned but not yet garbage-collected. It would be a good idea to
check the validity of that before using it in this context. My question
is - How to do that ?

···

--
Posted via http://www.ruby-forum.com/.

Love U Ruby wrote in post #1131229:

I wrote the code below :....
...
Somewhere I read that `ObjectSpace#each_object` can pick up objects that
are abandoned but not yet garbage-collected. It would be a good idea to
check the validity of that before using it in this context. My question
is - How to do that ?

Here's the result of a simple experiment I did. It shows that
`ObjectSpace#each_object` lists objects that have been deleted but not
yet garbage-collected:

include ObjectSpace

class Cat
  def initialize(n)
    @a =
    n.times {|i| @a << {}}
  end
end

def nobjects(msg)
  puts "\n#{msg}\n"
  # Note ObjectSpace#each_object enumerates over all
  # objects reported by ObjectSpace#count_objects.
  puts "number of hash objects = #{ObjectSpace.count_objects[:T_HASH]}"
end

n = 10000 # Create this number of empty hashes

nobjects("at start")
  # => at start
  # => number of hash objects = 77

cat = Cat.new(n)
nobjects("after creating an array of #{n} empty hashes")
  # => after creating an array of 10000 empty hashes
  # => number of hash objects = 10044

cat = nil
sleep(5)
nobjects("after setting cat => nil and waiting 5 secs")
  # => after setting cat => nil and waiting 5 secs
  # => number of hash objects = 10045

garbage_collect
nobjects("after forcing garbage collection")
  # => after forcing garbage collection
  # => number of hash objects = 29

···

--
Posted via http://www.ruby-forum.com/\.