如果我输入一个文件名而不在命令行中传递它(例如 ARGV 将为空)一切正常,但如果我在命令行中传递一个参数,我总是得到一个文件或目录不存在异常。
例如 file.rb test.txt 将排除所有内容。
start_dir = "file-io-samples/junk/"
begin
if ARGV.empty?
print "Enter a file name: "
file_name = start_dir + gets.chomp
else
file_name = start_dir + ARGV[0].chomp
puts "Writing to #{file_name}..."
end
fail "File Exists" if File.exist? file_name
puts "File ready: " if file = File.open(file_name, 'w')
while line = gets
break if line.chomp == "!"
file.puts line
puts "Written"
end
rescue Exception
puts "Exception Raised: #{$!}"
ensure
puts file.close
end