假设感兴趣的目录由变量target_dir 保存。那么我们想要:
require 'base64'
files_of_interest(target_dir).map { |f| Base64.encode64(File.read(file)) }
在哪里写方法files_of_interest。
这里有一些数据(Linux)。
ls -la testdir
drwxr-xr-x 1 cary cary 32 Jul 27 09:22 .
drwxr-xr-x 1 cary cary 346 Jul 27 09:22 ..
-rw-r--r-- 1 cary cary 0 Jul 27 09:22 file1
-rw-r--r-- 1 cary cary 0 Jul 27 09:22 file2
drwxr-xr-x 1 cary cary 28 Jul 27 11:41 subdir
ls -la testdir/subdir
drwxr-xr-x 1 cary cary 28 Jul 27 11:41 .
drwxr-xr-x 1 cary cary 32 Jul 27 09:22 ..
-rw-r--r-- 1 cary cary 0 Jul 27 09:23 file3
drwxr-xr-x 1 cary cary 10 Jul 27 11:41 subsubdir
ls -la testdir/subdir/subsubdir
drwxr-xr-x 1 cary cary 10 Jul 27 11:41 .
drwxr-xr-x 1 cary cary 28 Jul 27 11:41 ..
-rw-r--r-- 1 cary cary 0 Jul 27 11:41 file4
案例1:构造testdir中所有非目录文件的数组
可以使用Dir::[]、Dir::glob 或Dir::foreach。
使用[]
def files_of_interest(target_dir)
Dir["#{target_dir}/*"].select { |f| File.file?(f) }
end
files_of_interest("testdir")
#=> ["testdir/file1", "testdir/file2"]
注意
Dir["#{target_dir}/*"]
#=> ["testdir/file1", "testdir/file2", "testdir/subdir"]
使用glob
def files_of_interest(target_dir)
Dir.glob("#{target_dir}/*").select { |f| File.file?(f) }
end
files_of_interest("testdir")
#=> ["testdir/file1", "testdir/file2"]
使用foreach
def files_of_interest(target_dir)
Dir.foreach(target_dir).map { |f| "#{target_dir}/#{f}" }.
select { |f| File.file?(f) }
end
files_of_interest("testdir")
#=> ["testdir/file1", "testdir/file2"]
注意
enum = Dir.foreach(target_dir)
#=> #<Enumerator: Dir:foreach("testdir")>
enum.to_a
#=> [".", "..", "file1", "file2", "subdir"]
见File::file?。请注意,我们可以将Array#select 替换为Array#reject,将File::file? 替换为File::directory?。
案例2:构造testdir中的所有文件及其嵌套的非目录子目录的数组
这里我们必须使用Dir::glob。
def files_of_interest(target_dir)
Dir.glob("#{target_dir}/**/*").select { |f| File.file?(f) }
end
files_of_interest("testdir")
#=> ["testdir/file1", "testdir/file2", "testdir/subdir/file3",
# "testdir/subdir/subsubdir/file4"]