require relative ruby
To require a Ruby file using the require_relative
keyword, you can follow these steps:
- Use the
require_relative
keyword followed by the path to the Ruby file you want to include. The path can be either absolute or relative to the current file.
For example, if you want to require a file named "example.rb" located in the same directory as your current file, you can use the following code:
require_relative 'example.rb'
The
require_relative
method loads the specified file and executes its contents in the current scope. This means that any methods, classes, or variables defined in the required file will be available in the current file.If the specified file cannot be found or there is an error during the loading process, a
LoadError
will be raised.It's important to note that the
require_relative
keyword is used specifically to require files that are relative to the current file. If you want to require a file that is not in the same directory as your current file, you can use therequire
keyword instead, followed by the absolute or relative path to the file.
That's it! By using the require_relative
keyword in Ruby, you can include and execute code from other Ruby files in your current file.