From: Christopher Dicely Date: 2009-03-08T17:52:25+09:00 Subject: Re: Can I access or find a object from it's instance variable? On Sat, Mar 7, 2009 at 6:55 PM, 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 :) > -- > Posted via http://www.ruby-forum.com/. Others have posted ways using ObjectSpace, which works; its always seemed to me though that if you know you are going to need to do something like that with objects of a particular class, that it may often make more sense to do something like this: class Foo attr_reader :key @@instances = Hash.new {|h,k| h[k] = []} def self.find(key_val) @@instances[key_val].first end def self.find_all(key_val) @@instances[key_val].dup end def key=(new_key) @@instances[@key].delete self @@instances[new_key] << self @key = new_key end def initialize(key_val) @key = key_val @@instances[key_val] << self end end