On Mon, Aug 25, 2008 at 7:30 PM, Jes=FAs Gabriel y Gal=E1n
<jgabrielygalan / gmail.com> wrote:
> On Sat, Aug 23, 2008 at 4:35 PM, Matthew Moss <matthew.moss / gmail.com> wr=
ote:
>> ## 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 =3D (`uptime`.match /up (.*),.*user/)[1].delete(" ")
> captures =3D (uptime.match /((\d+)days,)?(\d+):(\d+)/).captures[1..-1]
> elapsed_seconds =3D 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 bo=
oted
less than 1 hour ago. So here is my revised solution, also compacting a lit=
tle
bit things, using only one regexp:

captures =3D (`uptime`.match /up (?:(?:(\d+) days,)?\s+(\d+):(\d+)|(\d+)
min)/).captures
elapsed_seconds =3D captures.zip([86440, 3600, 60, 60]).inject(0) do
|total, (x,y)|
=09total + (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 n=
ow.

Jesus.