the12 the12 - 1 month ago 6
Ruby Question

Why is the "./" (dot + forward slash) needed in Ruby files when using the require keyword?

In Windows, when attempting to place Ruby dependency files into a Ruby file, why is the "./" (dot + forward slash) necessary when typing out the file directory? Oddly enough it is only needed when using the

require
keyword and not the
load
keyword.

i.e.:
module.rb (the dependency)

module SomeModule
def someMethod
puts "hello"
end
end


method.rb

require "./module.rb"
#require "module.rb" does not work

class Animal
include SomeModule
end

class Person
include SomeModule
end

animal = Animal.new
animal.someMethod

person = Person.new
person.someMethod

#irb --> need to also write require " ./method.rb" to call it

Answer

It is only needed when using the require keyword and not the load keyword. Why?

load, require and require_relative are all methods which take a filename as an argument. They need to locate the filename passed an an argument which they do by checking the LOAD PATH which can be accessed using the global variable $LOAD_PATH or $:

Both load and require_relative act as if the current directory (designated by the .) is part of the LOAD_PATH so they are able to locate the file within the LOAD PATH when ruby searches it.

However when require is used, it does not add the current directory to the LOAD PATH so once ruby searches it, it doesn't find the file. This is why you have to explicitly tell ruby about the current_directory and how to locate the file using ./ which is just a path to the folder from the current directory.

If you don't want to add ./, you have to add the current directory to your Load Path

$: << '.'
require 'module.rb'

This will work as the current directory is now in the load path which is where ruby will search for the file.

Comments