Just Matt for now
Just Matt for now

Reputation: 89

Ruby require_relative path

So just to be perfecty clear.... Ruby can't handle

require 'filename'

for a file in the same directory.

*Regardless of where the script is being executed.

**But even if it is being executed from the same location.

I am reasonably new to programming but.... I must be missing something here. Security risk notwithstanding

Rails is happy with it's own load path situation so it all works nicely. But as soon as I want to run a script over one of these files "ruby says no".

Could someone help me please?

Thanks @pcm (too much to write in a comment)

Confidence it a low tripwire in the newb game.

Okay. Lesseons learned.

Don't fight with rails: Just allow your tests to catch any playing around with tricky refactors. Yeah.. Newbs, just wear the pain with the testing ecosystem straight off the bat.

require './filename' 

will only work when the $ruby script.rb is run from the same directory as the require ./filename files. This is because, chances are one of these files is going to have to open some other file for reading/editing/preporocessing, etc. e.g.

File.open("./file.txt").readlines.each do |line|

Now, even if both files are in the same location "I think" the location of where the script is invoked will be used to open it i.e.

$ruby path/to/file.rb 

and so throw a spanner.

But. If anyone could lend their experiences with this? Just so I know if I'm actually going crazy or not. I would have expected any compiler/interpreter to expect files to be in the directory/location of the file calling/using/accessing it if no filepath is specified?

Upvotes: 0

Views: 1495

Answers (1)

pcm
pcm

Reputation: 319

You'll need to add a dot and slash before the filename to require a file in the same directory.

require './filename'

The require keyword is not aware of the current working directory, necessitating the dot and forward slash. require_relative does not have the same limitation.

Upvotes: 1

Related Questions