2

I discovered this post about using bash

How to recursively find the latest modified file in a directory? (uses bash)

however I need to write this in ruby, I have a scenario with a network folder named "active", with many many sub directories, each sub directory has child directories and the children have child directories and so on. I need to return the date of the latest modified file contained in the lvl1 directory buried somewhere in its many child directories.

---------------------------
active | lvl1 | lvl2 | lvl3
       |      |      | lvl3
       |      | lvl2 |
       |      | lvl2 |
       |      | lvl2 | 
       | lvl1 |      |
---------------------------

edit with what I have currently which works great for returning file names, but im stuck on where to store the File.mtime() for each file occurance, I need to identify which lvl1 folder needs to be archived:

def walk(start)
  Dir.foreach(start) do |x|
    path = File.join(start, x)
    if x == "." or x == ".."
      next
    elsif File.directory?(path)
      walk(path)
    else
      puts x
    end
  end
end


path = 'folder\\path'

walk(path)
Community
  • 1
  • 1
alilland
  • 2,039
  • 1
  • 21
  • 42
  • The main task is how to descend. Once you decide how to do that, then it's easy to keep track of the age of a the most recent file. Be careful with recursive descent, as it can take a while on a big directory; All the various methods on the linked page should be explored before you settle on one because of the tradeoffs. Please read "[ask]". We need to see your effort toward solving the problem. Asking us how to do something is premature; You're supposed to research and try first, then show us what you tried. – the Tin Man May 27 '16 at 19:39
  • I edited my original question – alilland May 27 '16 at 20:56

1 Answers1

4

You can use Dir#glob method to find list of all files in a given directory and its subdirectories, and then, pick the file that has highest value for last modified time which can be obtained using File#mtime method.

Dir.glob("active/lvl1/**/*").max_by {|i| File.mtime(i)}
Community
  • 1
  • 1
Wand Maker
  • 18,476
  • 8
  • 53
  • 87