Introduction to $LOAD_PATH, require, load, include and extend in Ruby
Introduction to $LOAD_PATH, require, load, include and extend in Ruby
Ruby is a powerful object-oriented programming language with a rich library and module system. In Ruby, there are some key concepts and methods, such as $LOAD_PATH, require, load, include, and extend, which play an important role in organizing and using code. Let’s learn about them one by one.
- $LOAD_PATH:
Ruby's $LOAD_PATH is a global variable that stores a list of paths used by the Ruby interpreter to find and load files. When you import a file using the require or load methods, the Ruby interpreter searches the paths in $LOAD_PATH for the corresponding file. You can view the contents of $LOAD_PATH in the following ways:
puts $LOAD_PATH
This prints out a list of the current load paths.
- require:
require is the method in Ruby for loading library files. It accepts a string argument specifying the name of the file to load (the file extension can be omitted). The require method will search the path in $LOAD_PATH to find and load the corresponding file. Once the file is loaded, the classes, modules, and methods defined in it are available to the current code. For example:
require 'my_library'