Gaurav Manchanda
Gaurav Manchanda

Reputation: 544

Get Instance Name

Is there a way to get the name of the instance we created of a specific class in a class method?

This is what i'm trying to do:

module MyObjectStore
  values = {}
  temp=  {}
  define_method :add_check_attribute do |method,*args|
    if method.to_s =~ /=$/
      temp[method[0..-2]] = args[0]
    else
      instance_variable_get("@#{method}")
    end
  end
  define_method :method_missing do |method,*args|
    add_check_attribute(method,*args)
  end
  define_method :save do
    temp.each {|key,value| instance_variable_set("@#{key}",value)}
    values[self] = temp
    end
end

class C
  include MyObjectStore
end

a = C.new
a.id = 1
a.name = 'gaurav'
a.save

On the third-to-last line of the module, I'm trying to store the values of the object into the new hash having the instance name as the key.

Is anything like that possible?

I'm using self now, but it gives the whole object, not the instance name.

Upvotes: 3

Views: 3419

Answers (2)

Daren Thomas
Daren Thomas

Reputation: 70314

What should the instance name be? Unless you are talking about a specific attribute (like name), an instance doesn't really have a name. It can be referenced by variables that have a name, but the two are distinct.

So:

  • An object doesn't have a "name", except for some memory handle or similar mechanism used by the interpreter.
  • Variables have names, but can refer to different instances during program execution.
  • Different variables may refer to the same instance.

Given the last point, how should an instance decide on a "name"?

One way to solve this problem would be to use either the memory address or some kind of hashing function as the object name. A hashing function is a little tricky, since it will change as the object changes.

You can also decide to have an id or name field on all your instances and use that. Keep it unique. Have fun guaranteeing that. Go insane. Come back enlightened. Teach us.

Upvotes: 2

Linuxios
Linuxios

Reputation: 35793

Ruby objects have no name besides a memory address. Each object, though, has an object_id which is always unique. Using ObjectSpace._id2ref, instances and IDs are interchangeable. Here's an example:

id="Hello, World".object_id    => 82609910
ObjectSpace._id2ref(id)        => "Hello, World"
"Hello, Ruby".object_id        => 82721540

It is worth mentioning that the object id, although constant for an object across its lifetime, it is almost never constant between runs of a program, and different objects that have the exact same data will have different IDs:

"Hi".object_id                 => 82719050
"Hi".object_id                 => 82715090

Object IDs are also run dependent and OS dependent, etc. Never hard code object ids into your source code, only use ids that you got through object_id.

Upvotes: 6

Related Questions