-1

I tried running my code in a Ruby script from my terminal. Nothing happens when I run
ruby Main.rb.

# Main.rb

module Main
    class MyClass
        def initialize
            puts "Hello World" 
        end
    end
end
halfer
  • 19,824
  • 17
  • 99
  • 186
Nurdin
  • 23,382
  • 43
  • 130
  • 308

2 Answers2

3

You need to instantiate your class first, as your puts command will not execute until you invoke MyClass#new. For example:

module Main
  class MyClass
    def initialize
      puts "Hello World" 
    end
  end
end

Main::MyClass.new
Hello World
=> #<Main::MyClass:0x007f9d92144308>
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
1

Because it's loading the Module and then doing nothing with it. It never gets instantiated (initialized), only defined.

You define the module like so:

module Main
  class MyClass
    def initialize
      puts "Hello World" 
    end
  end
end

And then initialize it by making a new MyClass object. (On the end of the same file)

test = Main::MyClass.new
Hello World  
=> #<Main::MyClass:0x2979b88>

You can handle this in an even better way by only doing this when you run the file directly, not when it's loaded from another ruby file.

if __FILE__ == $0
  test = Main::MyClass.new
  puts test
end

This way you can do whatever you like when the code is run directly, for example, testing, but just load the module silently every other time.

When running the file directly, it will work as above, but when running this in IRB, you'll only see the following:

=> nil
Sam Pearman
  • 256
  • 1
  • 6