How to open files in relation to the home directory

Crash << 20> if the file exists:

open('~/some_file') 

However, I can do this:

 open(File.expand_path('~/some_file')) 

I have two questions:

  • Why doesn't open treat the tilde as pointing to the home directory?
  • Is there a smoother way than File.expand_path ?
+74
ruby
Mar 24 2018-10-10T00: 00Z
source share
4 answers
  • The shell (bash, zsh, etc.) is responsible for the expansion of wildcards, so in your first example there is no shell, therefore there is no extension. Using a tilde pointing to $HOME is a simple convention; indeed, if you look at the documentation for File.expand_path , it correctly interprets the tilde, but this is a function of the function itself, and not something that is inherent in the base system; In addition, File.expand_path requires the $HOME environment variable to be set correctly. Which leads us to a possible alternative ...
  • Try the following:

     open(ENV['HOME']+'/some_file') 

I hope this is enough. I personally find that using an environment variable is semantically clearer than using expand_path .

+92
Mar 24 '10 at 0:48
source share

Not sure if this was available before Ruby 1.9.3, but I think the most elegant solution is to use Dir.home , which is part of the kernel.

 open("#{Dir.home}/some_file") 
+99
Aug 14 2018-12-12T00:
source share

Instead of relying on the $HOME environment variable to set correctly, which can be a problem when using shared network computers for development, you can get this from Ruby using:

 require 'etc' open ("#{Etc.getpwuid.dir}/some_file") 

I believe that this identifies the currently logged-in user and gets their home directory, rather than relying on the $HOME global environment variable. This is an alternative solution to the above. I suppose.

+11
Feb 02 2018-12-12T00:
source share

I discovered a tilde problem, and a patch was created to add absolute_path which treats the tilde as a regular character.

In the file documentation:

 absolute_path(file_name [, dir_string] ) โ†’ abs_file_name 

Converts a path to an absolute path. Relative paths refer to the current working directory of the process if dir_string is not specified, in which case it will be used as a starting point. If the specified path starts with "~", it is NOT extended, it is considered as a normal directory name.

+2
Apr 15 '14 at 16:16
source share



All Articles