From: Brian Adkins Date: 2007-10-14T10:35:07+09:00 Subject: Re: top 10 last played mp3's On Oct 13, 8:35 pm, "Andreas S." wrote: > Konrad Meyer wrote: > > Quoth Andreas S.: > >> > know how to (correctly) compare a date to the return value of > > >> Dir['/share/music/**/*.mp3', '/share/music/*.mp3'].sort_by{|f| > >> File.atime}.reverse[0,10] > > > Or, if it's deeper than two levels: > > '**' takes care of that. Ah, you're right! I missed that also (even though the ** line is highlighted in the pickaxe now that I bother to read Dir#glob :) ). Before reading your explanation, I put the following together. It might be a little friendlier for handling multiple extensions I suppose, especially since the glob pattern isn't a real regex. require 'pp' require 'find' def n_recent_files n = 1, path = '.', exts = nil paths = [] Find.find(path) do |p| if File.file?(p) && ( exts.nil? || ( (ext = File.extname(p)) && !ext.empty? && exts.include?(ext) ) ) paths << p end end paths.sort! {|a,b| File.atime(b) <=> File.atime(a) }[0,n] end pp n_recent_files(10, '/home/brian/temp', '.mp3') pp n_recent_files(10, '/home/brian/temp', ['.mp3', '.ogg']) Some notes for the OP: 1) Welcome to Ruby! 2) Enumerable#sort_by can be slow in some cases, and by using sort (or sort! in this case), the comparison can be reversed to avoid calling Array#reverse on the entire array later. 3) It exhibits a benefit of 'duck typing' since both String and Array define include? the caller can pass in a single string or an array of strings for the extension parameter w/ no extra effort in the function. 4) Although the if expression is complicated, it has the advantage of only computing the file extension when necessary. Brian