Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 278
xpepermint Avatar asked Oct 28 '25 17:10

xpepermint


2 Answers

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.

like image 163
the Tin Man Avatar answered Oct 31 '25 06:10

the Tin Man


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.

like image 27
DigitalRoss Avatar answered Oct 31 '25 06:10

DigitalRoss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!