On Mon, Aug 25, 2008 at 7:30 PM, Jesù¸ Gabriel y GaláÏ <jgabrielygalan / gmail.com> wrote: > On Sat, Aug 23, 2008 at 4:35 PM, Matthew Moss <matthew.moss / gmail.com> wrote: >> ## Uptime Since... (#174) >> >> >> Nice and easy one this week. Your task is to write a Ruby script that >> reports the date and time of your last reboot, making use of the >> `uptime` command. > > My solution, tested in Ubuntu 8.04 and Fedora Core 2: > > uptime = (`uptime`.match /up (.*),.*user/)[1].delete(" ") > captures = (uptime.match /((\d+)days,)?(\d+):(\d+)/).captures[1..-1] > elapsed_seconds = captures.zip([86440, 3600, 60]).inject(0) do |total, (x,y)| > total + (x.nil? ? 0 : x.to_i * y) > end > puts "Last reboot was on #{Time.now - elapsed_seconds}" I realized that there was a case I wasn't taking into account: a machine booted less than 1 hour ago. So here is my revised solution, also compacting a little bit things, using only one regexp: captures = (`uptime`.match /up (?:(?:(\d+) days,)?\s+(\d+):(\d+)|(\d+) min)/).captures elapsed_seconds = captures.zip([86440, 3600, 60, 60]).inject(0) do |total, (x,y)| total + (x.nil? ? 0 : x.to_i * y) end puts "Last reboot was on #{Time.now - elapsed_seconds}" Anybody knows what's the format for a machine that's been up more than a day, but less than two? Is it "up 1 day" or "up 1 days"? Anyway I'm thinking changing that part of the regexp to "day(?:s)?" should suffice to take into account both cases, but I can't test it right now. Jesus.