質問

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.

役に立ちましたか?

解決 2

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

他のヒント

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 is used to join path components with separator File::SEPARATOR (normally /):

File.join('a', 'b', 'c')
# => "a/b/c"

Dir::glob returns filenames that matched with the pattern.

The given pattern /path/to/dir/**/* match any file recursively (below /path/to/dir).

From here:

glob -- Expands pattern, which is an Array of patterns or a pattern String, and returns the results as matches or as arguments given to the block.
*    -- Matches any file
**   -- Matches directories recursively
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top