sorcalin0x11
sorcalin0x11

Reputation: 21

Uninitialized constant (Name Error) creating object

I am trying to instantiate a new object by calling another class but I keep getting this error and I don't know why. I am still new to Ruby so I might be missing something here. I am getting this error:

TestA.rb:3 in `initialize': uninitialized constant TestA::TestB (NameError)
    from TestA.rb:7:in `new'
    from TestA.rb:7:in `<main>'

Here is my code: ** These two classes are in separate files **

class TestA
    def initialize
        @test = TestB.new
    end
end

test = TestA.new

class TestB
    def test_method
        print "Hello"
    end
end

Upvotes: 0

Views: 504

Answers (1)

Krzysztof Safjanowski
Krzysztof Safjanowski

Reputation: 7438

You have to require file with test_b class definition. If its name is test_b.rb it will looks like:

require_relative "test_b"

class TestA
    def initialize
        @test = TestB.new
    end
end

test = TestA.new 

Upvotes: 2

Related Questions