James Gray
12/1/2006 7:15:00 PM
On Dec 1, 2006, at 12:57 PM, Blake Miller wrote:
> i'm trying to do this, and I'm stuck
I've tried to answer your question and Rubyify your code a bit:
class YHolder
def initialize
@ys = Array.new
end
def add_y(y)
@ys << y
end
alias_method :<<, :add_y
def fetch_by_id(id)
@ys.find { |y| y.object_id == id }
end
alias_method :[], :fetch_by_id
end
class Y; end
class X < Y; end
holder, ids = YHolder.new, Array.new
10.times do
new_y_or_x = [Y, X][rand(2)].new
ids << new_y_or_x.object_id
holder << new_y_or_x
end
p holder # show the collection
# pick one by id
pick = ids[3]
p pick
p holder[pick]
# >> #<YHolder:0x1e2928 @ys=[#<Y:0x1e289c>, #<X:0x1e2874>, #<X:
0x1e284c>,
# >> #<Y:0x1e2824>, #<X:0x1e27fc>, #<Y:
0x1e27d4>,
# >> #<Y:0x1e27ac>, #<X:0x1e2784>, #<X:
0x1e275c>,
# >> #<Y:0x1e2734>]>
# >> 988178
# >> #<Y:0x1e2824>
__END__
Hope that helps.
James Edward Gray II