Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion about Dir[] and File.join() in Ruby

Tags:

file

ruby

dir

I meet a simple program about Dir[] and File.join() in Ruby,

blobs_dir = '/path/to/dir'
Dir[File.join(blobs_dir, "**", "*")].each do |file|
       FileUtils.rm_rf(file) if File.symlink?(file)

I have two confusions:

Firstly, what do the second and third parameters mean in File.join(@blobs_dir, "**", "*")?

Secondly, what's the usage the Dir[] in Ruby? I only know it's Equivalent to Dir.glob(), however, I am not clear with Dir.glob() indeed.

like image 452
dj199008 Avatar asked Feb 21 '14 07:02

dj199008


2 Answers

File.join(blobs_dir, "**", "*")

This just build the path pattern for the glob. The result is /path/to/dir/**/*

** and *'s meaning:

*: Matches any file
**: Matches directories recursively

So your code is used to delete every symlink inside the directory /path/to/dir.

like image 197
xdazz Avatar answered Sep 20 '22 07:09

xdazz


File.join() simply concats all its arguments with separate slash. For instance,

File.join("a", "b", "c")

returns "a/b/c". It is alsmost equivalent to more frequently used Array's join method, just like this:

["hello", "ruby", "world"].join(", ")
# => "hello, ruby, world"

Using File.join(), however, additionaly does two things: it clarifies that you are getting something related to file paths, and adds '/' as argument (instead of ", " in my Array example). Since Ruby is all about aliases that better describe your intentions, this method better suits the task.

Dir[] method accepts string or array of such strings as a simple search pattern, with "*" as all files or directories, and "**" as directories within other directories. For instance,

Dir["/var/*"]
# => ["/var/lock", "/var/backups", "/var/lib", "/var/tmp", "/var/opt", "/var/local", "/var/run", "/var/spool", "/var/log", "/var/cache", "/var/mail"]

and

Dir["/var/**/*"]
# => ["/var/lock", "/var/backups", "/var/backups/dpkg.status.3.gz", "/var/backups/passwd.bak" ... (all files in all dirs in '/var')]

It is a common and very convinient way to list or traverse directories recursively

like image 39
lobanovadik Avatar answered Sep 22 '22 07:09

lobanovadik