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.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With