0

我需要从调用方法 f 的类中返回一个类名。没有继承怎么办?还有……有可能吗?!

我正在使用 Ruby 1.9.2。

class B
  def f
    #need return class A
  end
end

class A
  attr_reader :a
  def initialize()
    @a = B.new
  end
end

A.new.a.f #=> A
4

3 回答 3

4

你可以这样做:

class B
  def f
    @blabla.class.name
  end
  def initialize(obj)
    @blabla=obj
  end
end
class A
  attr_reader :a
  def initialize()
    @a = B.new(self)
  end
end

A.new.a.f
    => "A"
于 2012-11-09T08:20:50.160 回答
0

您是要从字面上返回 class A,还是要动态确定调用者的类?如果是后者,那么在没有对 Ruby 内部结构进行非常奇怪的黑客攻击的情况下,没有一种安全的方法可以做到这一点,因此更改设计以解决此约束通常是一个更好的主意(通常通过注入构造函数或添加访问器,正如其他答案所建议的那样)。但是如果你想明确地返回 class A,这是一个简单的答案......

类是 Ruby 中的对象,存储在常量中。在调用方法之前,不会评估方法主体中的常量,因此在这种情况下,您可以简单地A从您的方法中返回:

class B
  def f
    A
  end
end

class A
  attr_reader :a
  def initialize()
    @a = B.new
  end
end

A.new.a.f #=> A
于 2012-11-09T13:49:06.577 回答
0

davidrac 解决方案的替代版本,除了它使用绑定。对不起,我对绑定的了解不多,在这里我可能使用不正确,请有人编辑它,谢谢。抱歉,在我的情况下,您仍然必须至少通过绑定。

class B
  def initialize(caller_class)
    @caller_class = caller_class
  end

  def f
    @caller_class
  end
end

class A
  attr_reader :a

  def initialize()
    @a = B.new(self.class)
  end
end

puts A.new.a.f  #=> A

除此之外,我认为您还可以使用:

set_trace_func lambda { |event, file, line, id, binding, classname| #do sth with classname }

或尝试肮脏的黑客

caller(0).last.match(/:(\d+):/)[1] # get the line number of caller, then get the class

但是,如果您在两行中分别调用 A.new.af,这将不起作用

于 2012-11-09T13:38:52.820 回答