Chris Loonam
Chris Loonam

Reputation: 5745

Ruby saying file doesnt exist

I'm new to Ruby, and I am writing a test program just to get some of the features down. Here is the program

#!/usr/bin/env ruby

class FileManager
  def read_file(filename)
    return nil unless File.exist?(filename)
    File.read(filename)
  end
end

if __FILE__ == $0
  fm = FileManager.new
  puts "What file would you like to open?"
  fname = gets

  puts fm.read_file fname
end

As you can see, it is very simple. If I comment the first line of the read_file method, I get this error

No such file or directory - /Users/macuser/Projects/Aptana\ Studio\ 3\ Workspace/Ruby\ Test/text (Errno::ENOENT)
from /Users/macuser/Projects/Aptana Studio 3 Workspace/Ruby Test/ruby.rb:6:in `read_file'
from /Users/macuser/Projects/Aptana Studio 3 Workspace/Ruby Test/ruby.rb:15:in `<main>'

when I run the program and use this file: /Users/macuser/Projects/Aptana\ Studio\ 3\ Workspace/Ruby\ Test/text

However, if I run cat /Users/macuser/Projects/Aptana\ Studio\ 3\ Workspace/Ruby\ Test/text, it outputs Hello, world!, as it should.

I don't believe it's a permissions issue because I own the folder, but just in case I've tried running the program as root. Also, I have made sure that fname is the actual name of the file, not nil. I've tried both escaped and unescaped versions of the path, along with just text or the full path. I know for a fact the file exists, so why is Ruby giving me this error?

Upvotes: 0

Views: 141

Answers (2)

knut
knut

Reputation: 27875

With gets filename the filename includes a newline \n.

You have to remove it in your filename:

gets filename 
p filename        #"test.rb\n"
p File.exist?(filename) #false
p File.exist?(filename.chomp) #true

(And you don't need to mask the spaces)

Upvotes: 2

Chuck
Chuck

Reputation: 237110

It looks like you're shell-escaping your spaces even though gets does not go through a shell. You want to enter "/Users/macuser/Projects/Aptana Studio 3 Workspace/Ruby Test/text" instead of "/Users/macuser/Projects/Aptana\ Studio\ 3\ Workspace/Ruby\ Test/text".

Upvotes: 0

Related Questions