retrieving an object by it's id

T

Thomas Hafner

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
 
A

Aaron Patterson

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
 
T

Thomas Hafner

Aaron Patterson said:
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
 
R

Robert Klemme

Aaron Patterson said:
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.

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,228
Messages
2,571,157
Members
47,785
Latest member
deepusaini

Latest Threads

Top