Question

I'm starting with Ruby programming and I want to write a small script that involves the creation of a directory.

When I use system 'mkdir', '-p' '~/.dir' no directory is created. But when I change it to /home/name/dir everything works as expected. As I want to keep the script generic, how can I achieve the usual Unix/Linux semantics of ~/?

Was it helpful?

Solution

In Ruby, ~ has no special meaning in file paths. Even if it is used inside the parameter of a system call, it is not expanded by the underlying shell. Your code should have created a directory literally named ~ inside the current working directory, for example:

$ ruby -e 'system("mkdir", "-p", "~/.dir")'
$ ls
~
$ ls -A '~'
.dir

You have to use File.expand_path to expand the ~ to your home directory path:

File.expand_path('~')
# => "/home/toro2k"

In your example:

system('mkdir', '-p', File.expand_path('~/.dir'))

In Ruby you can also use FileUtils.mkdir_p to create directories:

require 'fileutils'
FileUtils.mkdir_p(File.expand_path('~/.dir'))

Update: as suggested by the Tin Man my latter example can be rewritten using the Pathname class as follows:

require 'pathname'
Pathname.mkpath(Pathname.new('~/.dir').expand_path)

OTHER TIPS

It points to hidden directory .dir just under your user's root directory.

here ~/ represents user's root directory.

~ is not related to directory semantics in Ruby.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top