以创建的顺序从目录中获取文件?

时间:2011-03-29 13:21:06

标签: ruby-on-rails ruby

现在我写了这个逻辑..

  def get_file_names
    @files = []
    Find.find("#{BACKUP_FILE_DIR}") do |path|
      file_stat = File.stat path
      @files << {
        :name => File.basename(path,".*"),
        :mtime => file_stat.mtime,
        :path => path
      }
    end
    @files.delete_at(0)
    @files = @files.sort_by { |file| file[:mtime] }
    @file_names = []
    @files.each do |f|
      @file_names << [f[:name],f[:path]]
    end
  end

我怎样才能改进这种方法?

1 个答案:

答案 0 :(得分:0)

你需要在File :: Stat中使用“ctime”而不是mtime

mtime : time last modified
ctime : time created

试试这个:

# recursively collect file names based on ctime:
#
def get_file_names( dir )
  Dir.chdir(dir)
  Dir.entries(dir).each do |f|
   # next if f == '.'
   # next if f == '..'
    next if f =~ /^\./    # ignore dot-files and dot-directories                                    

    full_filename = File.join( Dir.pwd , f)

    if File.directory?( full_filename )
      get_file_names( full_filename )
    else
      stat = File::Stat.new( full_filename )
      @files_by_ctime[stat.ctime] ||= []
      @files_by_ctime[stat.ctime] << full_filename
    end
  end
  Dir.chdir('..')
end ; 1

@files_by_ctime = {}

get_file_names('/tmp')

@files_by_ctime.keys.sort.each do |ctime|
  puts "Created: #{ctime} : #{@files_by_ctime[ctime].inspect}"
end ; 1