Search code examples
rubyclassinstance-variables

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?


Solution

  • 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