As others said, working with the object_id directly is most probably the much better approach.
Anyway, something along this line might work in your case:
class Sample def method(&b) eval("local_variables.select {|v| eval(v.to_s).object_id == #{object_id}}", b.binding) end end n1 = Sample.new n2 = Sample.new n3 = n2 p n1.method {} #=> [:n1] p n2.method {} #=> [:n2, :n3] p Sample.new.method {} #=> []
It returns all (local) variables in the current scope referencing the callee object. If each of your objects is referenced by exactly one variable, this might be what you are looking for.
Suggested by Neil Slater: you can also use the gem binding_of_caller to simplify transferring the binding:
require 'binding_of_caller' class Sample def method binding.of_caller(1).eval( "local_variables.select {|v| eval(v.to_s).object_id == #{object_id}}" ) end end n1 = Sample.new n2 = Sample.new n3 = n2 p n1.method #=> [:n1] p n2.method #=> [:n2, :n3] p Sample.new.method #=> []
(tested with version 0.7.2 of the gem).