Retrieving an object by it's id

Hello,

how can I write a method f which fullfills the following
specification?

The function f has one Fixnum argument oi.
f(oi) == [true, obj], if there’s an object obj with obj.object_id == oi;
f(oi) == [false, nil], otherwise.

Regards
Thomas

On Mon, Jan 29, 2007 at 02:15:11AM +0900, Thomas H. wrote:

Hello,

how can I write a method f which fullfills the following
specification?

The function f has one Fixnum argument oi.
f(oi) == [true, obj], if there’s an object obj with obj.object_id == oi;
f(oi) == [false, nil], otherwise.

def f(oi)
g = [false, nil]
ObjectSpace.each_object { |a|
g = [true, a] if a.object_id == oi
}
g
end

Aaron P. [email protected] wrote/schrieb
[email protected]:

def f(oi)
g = [false, nil]
ObjectSpace.each_object { |a|
g = [true, a] if a.object_id == oi
}
g
end

Thanks, but:
4.object_id
=> 9
f(9)
=> [false, nil]
I’d expect [true,4], instead.

Regards
Thomas

On 28.01.2007 19:18, Thomas H. wrote:

Thanks, but:
4.object_id
=> 9
f(9)
=> [false, nil]
I’d expect [true,4], instead.

You don’t want to use #each_object for this - this is way to
inefficient. You want #_id2ref:

irb(main):006:0> ObjectSpace._id2ref 4.object_id
=> 4
irb(main):007:0> ObjectSpace._id2ref “foo”.object_id
=> “foo”

Kind regards

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs