Uninitialized constant- when trying to calculate

I am trying to use three modules,

First_Module.rb

module Raw_Data
  A = 10.0
  B = 20.0
end

Second_Module.rb

$LOAD_PATH << '.'
require "First_Module.rb"
module Do_Calc
  x= Raw_Data::A
  y= Raw_Data::B
  x = x * 12.0
  y = y * 1.5
  puts x
  puts y
  def Do_It.one(aa)
    aaa = aa * x
    puts (aaa)
  end

  def Do_It.two(bb)
    bbb = bb* y
    puts (bbb)
  end

end

Final_Result.rb

$LOAD_PATH << '.'

require "Second_Module.rb"

Do_It.one(2)

Do_It.two(10)

On the second module the code does show puts x & puts y

I get an error on the next line

def Do_It.one(aa)

“uninitialized constant Do_Calc::Do_It (NameError)”

How can this be fixed?

Hi Dave,

The error occurs because you’re calling “Do_It.one(aa)” but “Do_It” is not defined anywhere in your code.
To fix your error, you can define “Do_It” inside the “Do_Calc” module as a class and put “one” and “two” methods in the “Do_It” class:

module Do_Calc
  class Do_It
  
    x = Raw_Data::A * 12.0
    y = Raw_Data::B * 1.5
  
    def self.one(aa)
      aaa = aa * x
      puts aaa
    end
  
    def self.two(bb)
      bbb = bb * y
      puts bbb
    end
  
  end
end

In your Final_Result.rb, you can use these methods as below:

Do_Calc::Do_It.one(2)
Do_Calc::Do_It.two(10)

Just to note that, if you want to use variable x or y inside your methods, you may need to move these two lines x = Raw_Data::A * 12.0 and y = Raw_Data::B * 1.5 inside your methods or define x and y as class variables using @@.

I hope this helps!

Best,
Bobby the Bot

1 Like

That did it thanks:.xlorate