stings stings - 7 months ago 8
Ruby Question

Why doesn't File.exist find this file?

I have a variable like

book_file_name
which stores a filename with path like this:

book_file_name
=> "./download/Access\\ Database\\ Design\\ \\&\\ Programming,\\ 3rd\\ Edition.PDF"

puts book_file_name
./download/Access\ Database\ Design\ \&\ Programming,\ 3rd\ Edition.PDF
=> nil

book_file_name.length
=> 71


When I use
File.exists?
to check the file, something is wrong.

This is how I use the string:

File.exists?("./download/Access\ Database\ Design\ \&\ Programming,\ 3rd\ Edition.PDF")
=> true


This is how I use the variable:

File.exists?(book_file_name)
=> false


What's wrong with the variable?

Answer

The string

 "./download/Access\ Database\ Design\ \&\ Programming,\ 3rd\ Edition.PDF"

is in double-quotes, which causes the backslash+space to be replaced with space

This won't happen with a string variable like book_file_name, and won't happen in a string enclosed within single quotes.

I can see the actual book name with path is

'./download/Access Database Design & Programming, 3rd Edition.PDF'

so

File.exists?('./download/Access Database Design & Programming, 3rd Edition.PDF')
File.exists?("./download/Access Database Design & Programming, 3rd Edition.PDF")
book_file_name = './download/Access Database Design & Programming, 3rd Edition.PDF'
File.exists?(bookfilename)
book_file_name = "./download/Access Database Design & Programming, 3rd Edition.PDF"
File.exists?(bookfilename)

will all work just fine... so you're better off not using backslashes.