Graham Slick Graham Slick - 1 month ago 10
Ruby Question

Class'objects deleted randomly

I have a ruby class named

Table
, and I'm iterating over a csv file to create an object of this class for every row if this row's first element hasn't been seen yet.

Here is the code:

require 'csv'
class Table
def initialize(name)
@name = name
@columns = {}
end
end

csv_tables = File.read("db_apm.csv")
csv_tables = CSV.parse(csv_tables, :headers => true)
csv_tables.each_with_index do |row, index|
# Check if object with the name present at row[0] has already been created
if ObjectSpace.each_object(Table).find { |object| object.instance_variable_get(:@name) == row[0] }.nil?
table = Table.new(row[0])
p row[0]
end
p ObjectSpace.each_object(Table).to_a.count
end
p "Final count"
p ObjectSpace.each_object(Table).to_a.count


The csv file never changes, but I'm seeing some weird results:


  1. First, the count before the end of the each loop restarts at 0 during the same run of the script (I can see 1, 2, 3, ... 50, 1 , 2 , 3 ).

  2. Also, the final count changes between each run of the script. I sometimes get 17, or I can get 204 etc, it seems very random.



I don't understand why this is happening since the file isn't changing, and the code is pretty straightforward.

Here is a small extract of the file:

LOG_RECHERCHE
LOG_RECHERCHE
LOG_RECHERCHE
LOG_RECHERCHE
LOG_RECHERCHE
INTERVENTION
INTERVENTION
INTERVENTION
INTERVENTION
INTERVENTION
INTERVENTION
INTERVENTION
INTERVENTION
INTERVENTION
INTERVENTION
INTERVENTION
INTERVENTION
SUIVI_SCRIPT_SQL
SUIVI_SCRIPT_SQL
SUIVI_SCRIPT_SQL
SUIVI_SCRIPT_SQL
VUE_COMPILE_RENCONTRE
VUE_COMPILE_RENCONTRE
VUE_COMPILE_RENCONTRE
VUE_COMPILE_RENCONTRE
VUE_COMPILE_RENCONTRE
VUE_COMPILE_RENCONTRE


For this, the final count should be 4. I'm not sure the issue will occur with a small part of the file (the final count should be about 200 with the whole file).

Is ruby deleting objects for some reasons ?

Answer

There is a memory management mechanizm called garbage collection.

In Ruby it is implemented in GC module.

What it does, is removing objects, which are no longer used/referenced, to optimize memory usage.

Since you are not storing your created objects of Table class anywhere, GC treats them as garbage, and collects.

You can inspect the ObjectSpace by disable'ing garbage collection before the loop, for example.