Hi
I have found this tutorial
where there is the following class:
class Person
attr_accessor :fname, :lname
def initialize(fname, lname)
@fname = fname
@lname = lname
end
def to_s
@lname + ", " + @fname
end
def self.find_by_fname(fname)
found = nil
ObjectSpace.each_object(Person) { |o|
found.push(o) if o.fname == fname
}
found
end
end
Is it possible to add a self.delete that will delete the entry found by
the self.find_by_fname?
/Emil
On Fri, Feb 17, 2012 at 10:46 AM, Emil E. [email protected]
wrote:
@fname = fname
found.push(o) if o.fname == fname
}
found
end
end
That’s an awful and inefficient way to do it. A proper implementation
would at least hold an Array or Hash with all Persons in some global
place instead of resorting to ObjectSpace. ObjectSpace is a tool for
rather special situations and finalization handling.
Is it possible to add a self.delete that will delete the entry found by the
self.find_by_fname?
No. What would “deleting” mean here? There can be arbitrary many
references pointing to that instance found (including null, if GC has
not reclaimed an unreachable object):
~$ ruby19 -e
‘s=“foo”;id=s.object_id;s=nil;ObjectSpace.each_object(String){|st|
p st if st.object_id == id}’
“foo”
s is unreachable yet you see it through ObjectSpace.
Kind regards
robert