DO NOT RELY ON ObjectSpace for this functionality when the GC collects you will lose these objects because Ruby sees them as unneeded.
This is the general concept of what you are intending to do
class Foo
attr_reader :boos
def initialize(k)
@boos = (1..k).map {|b| Boo.new(b) }
end
def find_boo_with(x)
@boos.find {|b| b.a == x }
end
end
class Boo
attr_reader :a
def initialize(a)
@a = a
end
end
Then you can do this
f = Foo.new(10)
f.boos
#=> [#<Boo:0x256f428 @a=1>,
#<Boo:0x256f3b0 @a=2>,
#<Boo:0x256f368 @a=3>,
#<Boo:0x256f338 @a=4>,
#<Boo:0x256f2f0 @a=5>,
#<Boo:0x256f2d8 @a=6>,
#<Boo:0x256f2a8 @a=7>,
#<Boo:0x256f290 @a=8>,
#<Boo:0x256f278 @a=9>,
#<Boo:0x256f260 @a=10>]
f.find_boo_with(9)
#=> #<Boo:0x256f278 @a=9>
I hope this helps but you really should look into something like RubyMonk, or TryRuby to get a better understanding of how PORO (Plain Old Ruby Objects) work.
You could also do it this way if you really wanted your find methodology just know that no Boo in this case will ever be collected as they will all be stored in a class instance variable called @all_boos which could casue memory issues depending on what a Boo is and how many of them you are creating.
class Boo
class << self
def all_boos
@all_boos ||= []
end
def find(x)
@all_boos.find {|boo| boo.a == x }
end
alias_method :all, :all_boos
end
attr_reader :a
def initialize(a)
@a = a
self.class.all_boos << self
end
end
Then you can do
10.times {|i| Boo.new(i) }
Boo.all
#=> [#<Boo:0x256f428 @a=1>,
#<Boo:0x256f3b0 @a=2>,
#<Boo:0x256f368 @a=3>,
#<Boo:0x256f338 @a=4>,
#<Boo:0x256f2f0 @a=5>,
#<Boo:0x256f2d8 @a=6>,
#<Boo:0x256f2a8 @a=7>,
#<Boo:0x256f290 @a=8>,
#<Boo:0x256f278 @a=9>,
#<Boo:0x256f260 @a=10>]
Boo.find(9)
#=> #<Boo:0x256f278 @a=9>
allmethod that gives me back all the object in one array. Just not sure how to pick the right one now.Boo.find_by_xxxwill not do what you want because this relies on AR and SQL. What you have here the best way to implement would be an instance method of Foo.