可以将实例化的类分配给Ruby中的类变量吗?

时间:2015-11-01 16:47:00

标签: ruby

是否可以实例化A类并将其分配给B类中的类变量来调用B中的A方法?

class A
  ...
end

class B
  @@a = A.new

  def method_B
    @@a.method_A
  end
end

1 个答案:

答案 0 :(得分:1)

您可以在模块中包装方法,并在类中包含include(仅限实例方法)

module Foo
  def method_A
    p 'hello'
  end
end

class B
  include Foo
  def method_B
    method_A
  end
end

B.new.method_B