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

Is it possible to set a restriction on the Dir.each method? I would like to get only the last 10 files (sorted by creation date).

Example:

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

thank.

+3
source share
3 answers

This is one of those cases where it would be more efficient to ask the underlying OS to do the hard work, especially if you are combing many files:

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

On Mac OS, which opens the shell, sort all * .json files by creation date in reverse order, returning the last ten. The names will be returned in the string, so it splitsplits them into an Array at the ends of the lines.

ls tail C-, , Ruby, .

. Windows , . Linux .

+3

10 ctime...


Dir['*'].map { |e| [File.ctime(e), e] }.sort.map { |a| a[1] }[-10..-1]

#map{} ctime, , [ctime, fname], .

+2

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

script, .atime http://ruby-doc.org/core/classes/File.html#M002547

.

0

Source: https://habr.com/ru/post/1778668/


All Articles