2016-07-28 166 views
0

我有以下结构如何从另一个类中调用另一个类的方法?

class A 
     def method1 
     end 
end 

class B 
     @my = A.new 
     def classATest 
      @myT.method1 
     end 

     def newTest 
      classATest 
     end 
end 

class C 
     newB = B.new 
     newB.newTest 
end 

当我运行的C类,它给我的错误,它找不到类的方法1(方法newtest,调用方法classATest,它调用使用全局变量的方法1。我究竟做错了什么?这难道不是可以吗?

+0

Ruby的一个惯例是使用* snake-case *作为方法和变量的名字,这意味着你可以写'new_test'和'class_a_test'(或者可能'classA_test')。你不需要那样做,但我们99%的人都这么做。当你有一些时间的时候,你可能想看看[Ruby Style Guide](https://github.com/styleguide/ruby/)。 –

回答

2

你行,说@my = A.new没有做什么有用的东西。它让一个新的对象,并作为 B的实例变量赋值,但该类型的变量不能不需要额外的努力就可以被B的实例使用,你应该用下面的代码替换该行:

def initialize 
    @myT = A.new 
end 

另外,你有一个错字:你在一个地方写了@my,在另一个地方写了@myT

或者,保留代码的方式,并用常数名称替换@my@myT,例如MyA。 Ruby中的常量以大写字母开头,可以按照您尝试使用此变量的方式使用。

+0

“额外的努力”是“def newTest; self.class.instance_variable_get(:@ my).send:method1; end'。类实例变量'@ a'和实例变量'@ a'与日夜不尽相同。如果它们被命名为“@ a”和“@ b”,它们也不例外。返回值是'nil',因为'method1'返回nil。如果将'method1'更改为'def method1; “喜”;结束','hi''会被退回。 –

+0

...但是,但是,我测试了它。 –

+0

糟糕,我收回了我之前的评论。我真正的意思是,对'send'的调用是不必要的,因为'method1'是公共的。在某个时间点,你需要'send',因为'instance_variable_get'是私有的。 –

相关问题