From: Robert Klemme Date: 2009-11-02T17:33:19+09:00 Subject: Re: mtime.max 2009/10/31 Paul Smith : > On Sat, Oct 31, 2009 at 1:38 AM, Derek Smith > wrote: >> Hi All, >> >> My goal is to get the oldest file using mtime.to_i then delete it. >> However my >> puts stats.to_a.max does not seem to print out the oldest mtime >> data/file, rather its printing out the 2nd to oldest file; >> prod_db_bkup_Tue2009-10-271455.gz >> >> Correct me please and show me the code. >> >> thx! >> >> >> d=Date.today >> t=Time.now >> require 'enumerator' >>    stats = Hash.new >>    DB_BKUP1.each do |dbfile| >>        stats[dbfile] = [File.stat(dbfile).mtime.to_i] >>    end >>    puts stats.to_a,"\n\n" >>    puts stats.to_a.max > > This line is sorting the hash by the key, i.e. the filename.  You'll > see that Tue is alphabetically after Thu and Fr, and 271642 is after > 271455. > > instead, try > > puts stats.sort {|x,y| x[1] <=> y[1]}.max > > This explicitly sorts by the 2nd value in the to_a array, which is the mtime. There is no point in first sorting and then using max. Only one of the two makes sense: either you sort by your criterion and then take the first or last OR you find the max or min according to your criterion. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/