我可以或者应该通过ruby中的object_id属性找到一个对象吗?

时间:2021-03-25 20:26:59

When I make a new object, let's say

当我制作一个新物体时,让我们说吧

o = Object.new

This object has an id,

这个对象有一个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

我还使用Object类创建了其他几个对象。使用object_id属性让ruby找到对象'o'的最佳方法是什么?我在想类似的东西

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!

其中'search_results'将是与'search_id'对应的对象。此外,我肯定会欣赏一种完全不同的方法来索引对象并通过guid或其他东西检索它们。非常感谢!

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.

嗯,我想我真的只需要在数据库的上下文中考虑这个问题,只需使用MySQL查询或我选择查找对象的数据库。我想的越多,通过这个想象中的'find()'方法可以访问的唯一可能的东西是新创建或“活跃”的东西?很抱歉让这个问题变得糟透了。

1 个解决方案

#1


54  

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.

你应该这样做吗?我会把它留给你。存储具有可序列化id的对象的不太常见的方法(例如,在Array中并返回索引)。您可能遇到的一个问题是,如果您保留给对象的唯一“引用”是object_id,那么当您不查看时,GC可以收集该对象。

#1


54  

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.

你应该这样做吗?我会把它留给你。存储具有可序列化id的对象的不太常见的方法(例如,在Array中并返回索引)。您可能遇到的一个问题是,如果您保留给对象的唯一“引用”是object_id,那么当您不查看时,GC可以收集该对象。