I'm starting learning Ruby, one thing that I don't understand, why relative path for require directive doesn't work in ruby. It's something that works almost in every scripting language that I now (JSP, PHP...). I explain with a real example. I have a folder named shapes which contains 3 classes shape, rectangle and square. I have also another file test_shapes.rb from where I call and test my classes. When I import my classes to the main file like this:
require "./shape" require "./rectangle" require "./square"
I got error for files not found. When I include the name of my subfolder like this:
require "./shapes/shape" require "./shapes/rectangle" require "./shapes/square"
The code is perfectly working. Because I specified the whole path to the root directory of the project (the lib folder I think). When I include I include the absolute path to the hard disk, like this:
require "#{File.dirname(__FILE__)}/shape" require "#{File.dirname(__FILE__)}/rectangle" require "#{File.dirname(__FILE__)}/square"
It's also working perfectly.
So, I just want some explanation if know why the first import method (the relative path to the current folder) in not working.
Or you can use expand_path to convert relative path to absolute. Or you can calculate relative path between two dirs. require 'pathname'; puts Pathname. new('/').
require_relative allows you to "load a file that is relative to the file containing the require_relative statement". With require , ./ indicates a path that is relative to your current working directory. – Ajedi32.
Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy. A single dot represents the current directory itself.
Unlike absolute paths, relative paths contain information that is only relative to the current document within the same website which avoids the need to provide a full absolute path. In simple words, relative path refers to a path relative to the location of the current webpage.
Relative path is based on working dir. I assume that there is main file on the same directory. If you run ruby ./shapes/main.rb
on project root, ruby try to find {project_root}/shape.rb
, not {project_root}/shapes/shape.rb
. It doesn't work.
You need to use require_relative
like below.
# {project_root}/shapes/main.rb require_relative './shape' require_relative './rectangle' require_relative './square'
You are using relative path. And they are relative to the place where your script is executed. Generally it is bad idea. You should use either absolute path, either relative path to exact file where require
is executed.
require File.expand_path("../shape", __FILE__)
PS: require_relative looks more laconic
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With