Ruby Dir['**/*'] limit?
Is it possible to set a limit on D开发者_如何学Goir.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.
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.
The last 10 files by ctime...
Dir['*'].map { |e| [File.ctime(e), e] }.sort.map { |a| a[1] }[-10..-1]
The second #map{}
just strips off the ctime objects so if you don't mind working directly with the array of [ctime, fname]
you can leave it off.
Try each_with_index http://ruby-doc.org/core/classes/Enumerable.html#M003141
Dir[...].each_with_index do |f, i|
break if i == 10
puts f
end
And create a script to use the .atime http://ruby-doc.org/core/classes/File.html#M002547
to create a conventional naming system based on date.
精彩评论