From: Robert Klemme Date: 2012-02-17T19:57:37+09:00 Subject: Re: delete from class On Fri, Feb 17, 2012 at 10:46 AM, Emil Enemærke wrote: > Hi > > I have found this tutorial http://juixe.com/techknow/index.php/2007/01/22/ruby-class-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 > ### 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 -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/