0

假设我有

module A
  include module B

  class C
    def methodC
      B.methodB
    end
    def self.methodD 
      somemethod
    end
  end
end

module B
  def self.methodB
    A::C.methodD
  end    
end

instance = A::C.new

如何避免使用此类级别的方法(self)?事实上,我怎么能打电话methodBinstance

4

2 回答 2

1

如果我很好理解,在某个方法中调用当前实例的关键字是self. 所以你可以使用

def methodC
     self.methodB
end

并删除self里面self.methodB

(顺便说一句,除非methodD必须要在里面class C,你可以把它放在里面moduleB然后删除A::Cfor methodD;))

于 2013-08-13T18:56:22.097 回答
0

试试这个

# define moduke B first so that, it can be included in A
module B
  def methodB
    A::C.methodD
  end
end

module A

  class C
    include B # include B here  

    def methodC
      methodB
    end

    def self.methodD 
      somemethod
    end
  end
end

instance = A::C.new
p instance.methods.grep /methodB/
=> [:methodB]
于 2013-08-13T19:24:08.533 回答