Ruby doesn't believe any external files exist and i don't know why?

Viewed 36

I've been learning ruby through this YouTube tutorial https://youtu.be/t_ispmWmdjY

So far it's been going well until I got to the section about reading or writing files, for whatever reason the external file which I named "demons.txt" does not work and when I tried to run the code

File.open("demons.txt", "r")

I get this error

Ruby/practice2.rb:1:in `initialize': No such file or directory @ rb_sysopen - demons.txt (Errno::ENOENT)

I started to suspect it was because ruby couldn't find the file and sure enough when I ran

puts File.exist?("demons.txt")

I am given a "false" which makes absolutely no sense to me since I can clearly see the file I'm trying to read in the explorer within the same directory with the exact same name and it's starting to infuriate me that I can't even think of a possible solution, help!

1 Answers

When you execute a Ruby program, it will have a current directory. Make sure that the current directory when you execute the program is the directory that contains the file. For example:

cd ~/myproject/data    # Assuming this dir contains demons.txt
~/myproject/bin/myprogram

For additional debugging, include these lines (assuming Linux):

system("pwd")
system("ls -l demons.txt")

The first will show you what the currently directory is. The second will show you the directory entry for the file you are trying to open.

Related