Peter Peter - 1 year ago 124
Ruby Question

How to open files relative to home directory

The following fails with

Errno::ENOENT: No such file or directory
, even if the file exists:


However, I can do this:


I have two questions:

  1. Why doesn't
    process the tilde as pointing to the home directory?

  2. Is there a slicker way than

Answer Source
  1. The shell (bash, zsh, etc) is responsible for wildcard expansion, so in your first example there's no shell, hence no expansion. Using the tilde to point to $HOME is a mere convention; indeed, if you look at the documentation for File.expand_path, it correctly interprets the tilde, but it's a feature of the function itself, not something inherent to the underlying system; also, File.expand_path requires the $HOME environment variable to be correctly set. Which bring us to the possible alternative...
  2. Try this:


I hope it's slick enough. I personally think using an environment variable is semantically clearer than using expand_path.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download