user7434936
user7434936

Reputation:

How do I get the variable name(s) that an object is assigned to in Ruby?

Is there a way to get the variable names currently assigned to the object, by using the object ID for example?

class Example
end

ex1 = Example.new

ex1.object_id
  > 70184576592420

ex2 = ex1

Perhaps it would look something like this:

obj_id(70184576592420).var_names
  > [ex1, ex2]

Upvotes: 0

Views: 270

Answers (1)

Ilya
Ilya

Reputation: 13477

I would extend @sagarpandya82 answer:

local_variables.select do |e| 
  binding.local_variable_get(e).object_id == 70184576592420
end
#=> [:ex2, :ex1]

Just local_variables returns a list of all local variables.

Upvotes: 4

Related Questions