Jonny Peppers
Jonny Peppers

Reputation: 169

How to call another classes methods from another class?

I have the following structure

 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

When I run class C, it gives me the error that it cannot find method1 of Class A (method newtest, calls method classATest, which calls the method1 using a global variable. What am I doing wrong? Is this not allowed?

Upvotes: 0

Views: 1512

Answers (1)

David Grayson
David Grayson

Reputation: 87386

Your line that says @my = A.new is not doing anything useful. It's making a new object and assigning it as an instance variable of class B, but that kind of variable cannot be used by instances of B without extra effort. You should replace that line with:

def initialize
  @myT = A.new
end

Also, you had a typo: you wrote @my in one place and @myT in another.

Alternatively, keep the code the way you have it and replace @my and @myT with the name of a constant, such as MyA. Constants in Ruby start with capital letters, and can be used the way you are trying to use this variable.

Upvotes: 2

Related Questions