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.
For every object, Ruby offers a method called object_id. You guessed it, this represents a random id for the specific object. This value is a reference of the address in memory where the object is store. Every object has a unique object id that will not change throughout the life of this object.
The proper way to determine the "type" of an object, which is a wobbly term in the Ruby world, is to call object. class . Since classes can inherit from other classes, if you want to determine if an object is "of a particular type" you might call object.
In Ruby, we call them methods because everything is an object and all functions are called on objects. All methods are functions, but the reverse isn't necessarily true. "Hello world!" is an instance of the class String .
You can create objects in Ruby by using the method new of the class. The method new is a unique type of method, which is predefined in the Ruby library. The new method belongs to the class methods. Here, cust1 and cust2 are the names of two objects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With