Markus Siebert
Markus Siebert

Reputation: 69

Create object within class definition

I want to crate an instance of ClassB inside ClassA, and assign it to variable @test3.

This is my code:

module A
  module B
    class ClassA < Hash
      @test1 = Hash.new()
      @test2 = Object.new()
      @test3 = A::B::ClassB.new()

      def initialize(_name, _config = {})
        puts _name
        puts _config
        super()
      end
    end

    class ClassB < Hash
      def initialize(_config = {}, _parent = nil)
        puts _config
        puts _parent
        super()
      end
    end
  end
end

It is possible to set @test3 within the initialize method, but I have reasons not to do so. @test1 and @test2 work, but I get an error:

NameError: uninitialized constant A::B::ClassB

Why does this not work?

Upvotes: 0

Views: 77

Answers (3)

zkai
zkai

Reputation: 1

Ruby interpreter execute codes line by line, including inside class definition, you should keep this idea in mind. when ruby interpreter encounter @test3 = A::B::ClassB.new(), ClassB havn't been defined, this is why you get the NameError. to eliminate this error, you should move the definition of ClassB to the front of ClassA.

Upvotes: 0

Pierre Michard
Pierre Michard

Reputation: 1391

The reason is that your ruby interpreter parses your file sequentially, so that when it reaches the @test3 definition, ClassB is still not declared. If you can do so, the issue can be fixed by defining ClassB before ClassA, so that classB is defined when defining @test3:

module A
  module B
    class ClassB < Hash
      def initialize(_config = {}, _parent = nil)
        puts _config
        puts _parent
        super()
      end
    end

    class ClassA < Hash
      @test1 = Hash.new()
      @test2 = Object.new()
      @test3 = A::B::ClassB.new()

      def initialize(_name, _config = {})
        puts _name
        puts _config
        super()
      end
    end 
  end
end

Upvotes: 3

mbuechmann
mbuechmann

Reputation: 5740

You are using ClassB before defining it. If you switch the order of ClassA and ClassB your code works.

Upvotes: 1

Related Questions