我可以或应该通过 ruby​​ 中的 object_id 属性找到对象吗? [英] Can I or SHOULD I find an object by the object_id attribute in ruby?

查看:11
本文介绍了我可以或应该通过 ruby​​ 中的 object_id 属性找到对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我创建一个新对象时,比方说

When I make a new object, let's say

o = Object.new

这个对象有一个id,

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

我还使用 Object 类制作了其他几个对象.使用 object_id 属性让 ruby​​ 找到对象o"的最佳方法是什么?我正在考虑类似的东西

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)

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

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!

哈,我想我真的只需要在数据库的上下文中考虑这一点,只需使用 MySQL 查询或我选择的任何 DB 查询来查找对象.我想得越多,通过这个虚构的find()"方法可以访问的唯一可能的东西就是新创建的或活跃"的东西?很抱歉提出这个蹩脚的问题.

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.

推荐答案

是的,你可以:

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"

你应该这样做吗?我会把它留给你.使用可序列化的 id 存储对象的方法较少(例如,在数组中并返回索引).您可能会遇到的一个问题是,如果您对对象保留的唯一引用"是 object_id,则该对象可以在您不查看时被 GC 收集.

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.

这篇关于我可以或应该通过 ruby​​ 中的 object_id 属性找到对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆