From: Sean O'Halpin Date: 2009-03-08T13:07:50+09:00 Subject: Re: Can I access or find a object from it's instance variable? On Sun, Mar 8, 2009 at 2:55 AM, Aki Wakabayashi wrote: > Hello. > > Absolute newb here, and my very first post, so please bear with me...I > would like to be able to access an object with it's instance variable. I > simplified my example, but for instance: > > > class Foo >  attr_accessor :some_id > end > > > one = Foo.new('7a') > two = Foo.new('2t') > three = Foo.new('33') > > > Is it possible to use the instance variable @some_id to access the > object itself? I was thinking of creating a class method for class Foo > such as: > > class Foo >  attr_accessor :some_id > >  self.find(some_id) >    # somehow get an array of all the Foo objects, and iterate through > their >    # some_id attributes until a match(s) is found, return the object(s) >  end > end > > ...so I can do something like Foo.find('7a43') to access the object > 'one'. > > I am exhausted from searching how to get an array or hash of objects of > a given class, and I think I'm going in the wrong direction. Any > pointers will be greatly appreciated. > > > Thank you in advance :) Here's one way (not terribly efficient): class Foo attr_accessor :oid def initialize(oid) @oid = oid end def self.find(oid) found = nil ObjectSpace.each_object(self) do |o| if o.oid == oid found = o break end end found end end one = Foo.new('7a') two = Foo.new('2t') three = Foo.new('33') Foo.find('7a') # => # Regards, Sean