Search code examples
ruby-on-railsrubyfileglob

Ruby Dir['**/*'] limit?


Is it possible to set a limit on Dir.each method? I would like to retrieve only last 10 files (ordered by create date).

Example:

Dir[File.join(Rails.root, '*.json'), 10].each do |f|
  puts f
end 

Thx.


Solution

  • This is one of those times when it might be more efficient to ask the underlying OS to do the heavy lifting, especially if you're combing through a lot of files:

    %x[ls -rU *.json | tail -10].split("\n")
    

    On Mac OS that will open a shell, sort all '*.json' files by their creation date in reverse order, returning the last ten. The names will be returned in a string so split will break them into an Array at the line-ends.

    The ls and tail commands are really fast and doing their work in compiled C code, avoiding the loops we'd have to do in Ruby to filter things out.

    The downside to this is it's OS dependent. Windows can get at creation data but the commands are different. Linux doesn't store file creation date.