Sean O'Halpin
3/8/2009 4:08:00 AM
On Sun, Mar 8, 2009 at 2:55 AM, Aki Wakabayashi <zzyzx2001@gmail.com> 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
> =A0attr_accessor :some_id
> end
>
>
> one =3D Foo.new('7a')
> two =3D Foo.new('2t')
> three =3D 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
> =A0attr_accessor :some_id
>
> =A0self.find(some_id)
> =A0 =A0# somehow get an array of all the Foo objects, and iterate through
> their
> =A0 =A0# some_id attributes until a match(s) is found, return the object(=
s)
> =A0end
> 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 =3D oid
end
def self.find(oid)
found =3D nil
ObjectSpace.each_object(self) do |o|
if o.oid =3D=3D oid
found =3D o
break
end
end
found
end
end
one =3D Foo.new('7a')
two =3D Foo.new('2t')
three =3D Foo.new('33')
Foo.find('7a') # =3D> #<Foo:0x244c8 @oid=3D"7a">
Regards,
Sean