From: Robert Klemme Date: 2008-12-19T17:15:22+09:00 Subject: Re: Show newest file in directory? 2008/12/19 Mike Cargal : > Just a pet peeve.... but... Sorts are expensive and should be avoided when > possible. Finding min and max values are prime examples. > > So... > > newest = Dir.entries(dir).max {|a,b| (File.mtime(File.join(dir,a)) <=> > File.mtime(File.join(dir,b)))} While we're nitpicking... :-) In this case File.mtime is most likely the most expensive operation as it does IO (or at least has to travel into system call land). #max will invoke File.mtime multiple times for the same file. So, efficiency wise an explicit one pass solution is probably best: max = Time.at 0 file = nil Dir.open(dir) do |d| d.each do |f| mt = File.mtime(File.join(dir, f)) if mt > max max = mt file = f end end end puts file Btw, there is another nice short solution, which unfortunately also suffers the multiple #mtime per File issue (you can easily see this by placing "p f;" before the "File.mtime" in the block): puts Dir.open(dir) {|d| d.max_by {|f| File.mtime(File.join(dir, f))}} Kind regards robert -- remember.guy do |as, often| as.you_can - without end