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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)