Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

search - Can I or SHOULD I find an object by the object_id attribute in ruby?

When I make a new object, let's say

o = Object.new

This object has an id,

o.object_id 
#=> ########

I also make several other objects, using the Object class. What would be the best way to have ruby find the object 'o' by using the object_id attribute? I am thinking in terms of something like

search_id = o.object_id
search_result = Object.find(search_id)

Where 'search_results' would be the object corresponding to 'search_id'. Also, I would definitely appreciate an altogether different approach to indexing objects and retrieving them by a guid or something. Thanks so much!

Hah, well I guess I really just need to think about this in the context of a database and just use MySQL queries or those of whatever DB I choose to find the object. The more I think about it, the only possible things that would be accessible through this imaginary 'find()' method would be things that are newly created or 'active'? Sorry for making this a crappy question.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, you can:

irb(main):002:0> s1 = "foo"
#=> "foo"
irb(main):003:0> s2 = ObjectSpace._id2ref(s1.object_id)
#=> "foo"
irb(main):004:0> s2.object_id == s1.object_id
#=> true
irb(main):005:0> s2[0] = "z"
#=> "z"
irb(main):006:0> s1
#=> "zoo"

Should you do this? I'll leave that up to you. There are less geeky ways to store an object with a serializable id (e.g. in an Array and returning the index). One problem you may run into is that if the only 'reference' you keep to an object is the object_id, the object can be collected by GC when you're not looking.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...