I installed Ruby 1.9.2 on my Win 7 machine. Created a simple analyzer.rb
file. It has this one line:
File.open("text.txt").each {|line| puts line}
When I run the code, it gives me this error:
analyzer.rb:1:in `initialize': No such file or directory - text.txt (Errno::ENOENT)
from analyzer.rb:1:in `open'
from analyzer.rb:1:in `<main>'
Exit code: 1
I don't get it. There is a text.txt
file in the same directory as the analyzer.rb
file. I also tried feeding the absolute path of the file, C:\Ruby192\text.txt
, but no dice. What am I missing?
Start by figuring out what your current working directory is for your running script.
Add this line at the beginning:
puts Dir.pwd
.
This will tell you in which current working directory ruby is running your script. You will most likely see it's not where you assume it is. Then make sure you're specifying pathnames properly for windows. See the docs here how to properly format pathnames for windows:
http://www.ruby-doc.org/core/classes/IO.html
Then either use Dir.chdir
to change the working directory to the place where text.txt is, or specify the absolute pathname to the file according to the instructions in the IO docs above. That SHOULD do it...
EDIT
Adding a 3rd solution which might be the most convenient one, if you're putting the text files among your script files:
Dir.chdir(File.dirname(__FILE__))
This will automatically change the current working directory to the same directory as the .rb
file that is running the script.
ENOENT
means it's not there.
Just update your code to:
File.open(File.dirname(__FILE__) + '/text.txt').each {|line| puts line}
Please use chomp()
or chomp()
with STDIN
i.e. test1.rb
print 'Enter File name: '
fname = STDIN.gets.chomp() # or fname = gets.chomp()
fname_read = File.open(fname)
puts fname_read.read()
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