9

文件结构:

folderA/
 - folder1/
   - file1.rb
   - file2.rb
 - folder2/
   - folder1/
     - file1.rb
   - folder2/
     - file1.rb
 - file1.rb
 - file2.rb

使用下面的代码,我只能迭代folderA/file1.rbfolderA/file2.rb

# EDITTED
Dir.glob('folderA/*.rb') do |file|
  puts file
end

是否可以仅使用(不使用 Dir.foreach(dir)..if..)遍历所有.rb文件(包括子文件夹)?glob

PS红宝石 v.1.8.6

4

3 回答 3

24
Dir.glob('folderA/**/*.rb') do |file|
  puts file
end

来自官方文档

**
递归匹配目录。

于 2012-08-03T15:51:39.337 回答
2

试试这个:

Dir.glob('spec/**/*.rb') do |rspec_file|
  puts rspec_file
end

在此处阅读有关 glob的信息

于 2012-08-03T15:45:08.397 回答
2

这应该有效:

来源:http ://ruby-doc.org/stdlib-1.9.3/libdoc/find/rdoc/Find.html

require 'find'

Find.find('spec/') do |rspec_file|
    next if FileTest.directory?(rspec_file)
    if /.*\.rb/.match(File.basename(rspec_file))
        puts rspec_file
    end
end

在 ruby​​ 1.8.7 中测试

于 2012-08-03T15:58:18.133 回答