如何在ruby中获取调用者对象名称?

时间:2013-09-06 06:21:54

标签: ruby object

通常,从不同的对象A,B,C调用相同的方法X.是否可以从方法X中获取调用者对象(A,B,C)的名称

例如:

class Sample
  def method
    # what needs to be done here?
  end
end

n1 = Sample.new
n2 = Sample.new

n1.method #=> expected output is to print n1
n2.method #=> expected output is to print n2

4 个答案:

答案 0 :(得分:5)

不,这不起作用。想象如下:

n1 = Sample.new
n2 = n1

n2.method #=> ambiguous, both n1 and n2 would be valid

您可以为您的实例分配名称

class Sample
  attr_accessor :name
end

n1 = Sample.new
n1.name = :n1

n2 = Sample.new
n2.name = :n2


n1.name #=> :n1
n2.name #=> :n2

答案 1 :(得分:4)

正如其他人所说,直接使用object_id很可能是更好的方法。

无论如何,沿着这条线的某些东西可能适合你的情况:

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 {} #=> []

它返回引用被调用者对象的当前作用域中的所有(本地)变量。如果每个对象都被一个变量引用,则可能会这样做 是你在寻找的。

由Neil Slater建议:你也可以使用gem binding_of_caller来简化 转移绑定:

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 #=> []

(使用宝石版本0.7.2进行测试)。

答案 2 :(得分:3)

任何对象都可以通过其object_id标识:

class Sample
  def method
    puts self.object_id
  end
end

n1 = Sample.new
n2 = Sample.new

puts n1.object_id
n1.method

puts n2.object_id
n2.method

--output:--
2152302060
2152302060
2152302040
2152302040

变量名......不是那么多。

答案 3 :(得分:0)

只需返回self即可,

以下是一个例子:

class Sample
  attr_accessor :name
  def method
    puts self  
    puts self.name  
  end
end

n1 = Sample.new
n1.name = "Bangalore"
n2 = Sample.new
n2.name = "Chennai"


n1.method #=> expected output is to print n1
n2.method #=> expected output is to print n2


-------
Output: 
#<Sample:0x7f492f62c030> # n1 object
Bangalore # n1.name 
#<Sample:0x7f492f62bec8> # n2 object
Chennai #n2.name