stings stings - 1 year ago 58
Ruby Question

Why doesn't File.exist find this file?

I have a variable like

which stores a filename with path like this:

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

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

=> 71

When I use
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:

=> false

What's wrong with the variable?

Answer Source

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'


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'
book_file_name = "./download/Access Database Design & Programming, 3rd Edition.PDF"

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