Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File paths in Ruby

Tags:

file

ruby

So I want to make a file path relative to the directory it is in, in Ruby.

I have a project, and I want it to be able to find the file no matter what directory the project is unzipped into. (Say the code is run on different machines, for example) I can't figure it out for the life of me.

It seems for requires that I can do this:

require File.dirname(__FILE__) + '/comparison'

What can I do for a file that is in a different directory than my src folder?

Instead of listing,

file = 'C:/whole path/long/very_long/file.txt'

I'd like to say:

file = 'file.txt'

or

file = File.helpful_method + 'file.txt'
like image 887
Alex Baranosky Avatar asked Feb 27 '23 13:02

Alex Baranosky


1 Answers

file = File.join(File.dirname(__FILE__), '..', 'another_dir', 'file.txt')

Replace '..', 'another_dir' with the relative path segments that reach 'file.txt'.

like image 140
dan Avatar answered Mar 07 '23 06:03

dan