1.

How do you import files or packages or modules in ruby?

Answer»

In ruby, we can import with ‘load’ and ‘require’ KEYWORD is used to load packages or modules.

The load method INCLUDES the ruby file every time it is being executed.

   load ‘filename.rb’

The COMMONLY used require method includes the ruby file only once.

   require ‘filename’    require ‘./filename’

For example:

To import file with ‘require’ keyword

Create a file with hello.rb with following code IMPLEMENTATION

//--------start code-------------- class Hello  def print puts "Hello"  end end //-------end code-------------- Now create a new file with name print_hello.rb with following code implementation //------start code-------- require './hello' x = Hello.new x.print //----end code-------- Now run the above file from TERMINAL //----------------- $ ruby print_hello.rb Hello $ //----------- To import file with ‘load’ keyword Create a new file with name print_hello2.rb with following code implementation //------start code-------- load 'hello.rb’ x = Hello.new x.print //----end code-------- Now run the above file from terminal //----------------- $ ruby print_hello2.rb Hello $ //-----------


Discussion

No Comment Found