0

尝试编写一个脚本,该脚本将在目录和子目录中搜索特定文件。我想知道某个或多个目录是如何调用方法的。

这是我尝试过但失败的:

def display_directory(path)
list = Dir[path+'/*'] 
return if list.length == 0

list.each do |f|     

  if File.directory? f #is it a directory?
    if File.directory?('config')
      puts "this is the config folder"
    end
    printf "%-50s %s\n", f, "is a directory:".upcase.rjust(25)
  else
    printf "%-50s %s\n", f, "is not a directory:".upcase.rjust(25)
  end
 end
end


start = File.join("**")
puts "Processing directory\n\n".upcase.center(30)
display_directory start

这就是我想要发生的事情。

        app
app/controllers
app/helpers
app/mailers
app/models
app/models/bugzilla
app/models/security
app/views
app/views/auth
app/views/calendar
app/views/layouts
app/views/step
app/views/step_mailer
app/views/suggestion
app/views/suggestion_mailer
app/views/task
app/views/user
bin
--------------------------------------
config <----------(call method foo)
config/environments
config/initializers
config/locales
--------------------------------------
db
db/bugzilla
db/migrate
db/security
lib
lib/tasks
log
public
public/images
public/javascripts
public/stylesheets
script
script/performance
script/process
--------------------------
test <---------(call method foobar)
test/fixtures
test/fixtures/mailer
test/functional
test/integration
test/performance
test/unit
--------------------------
vendor
vendor/plugins
4

2 回答 2

0

反而

if File.directory?('config')

尝试

if f.path.include?('config')

但这适用于名称上有配置的每个目录。您可以放置​​更大的子字符串以进行更好的匹配。

do..end此外,它在多行块和{..}单行的 ruby​​ 中使用非常惯用。

于 2013-05-08T20:32:05.127 回答
0

我想出了一个办法。这很好用。我添加了一种方法来显示到达时提到的目录中的所有文件。

def special_dir(path)
  puts "------------------------------------"
  sp_path = Dir.glob(File.join(path,"*","**"))
  sp_path.each do |cf|
    puts "\t" + cf
  end
end

def walk(path)
  list = Dir[path+'/*'].reject{ |r| r['doc'] || r['tmp']}
    list.each do |x|
      path = File.join(path, x)
      if File.directory?(x)
        if x =~ /config/ or x =~ /test/  
          special_dir(x)
        else 
          puts "#{x}"
          walk(path)
        end
      else
        #puts x
      end
    end
  end

  start = File.join("**")

  walk start
于 2013-05-09T15:35:07.897 回答