tags:

views:

39

answers:

3

I want to take the current time and store it in hash and then when I check it again compare the current time to the stored time.

t1 =Time.now
time = "#{t1.hour}" + "#{t1.min}" + "#{t1.sec}"
oldtime = Hash.new(time)
puts "Old time is #{oldtime}"
puts "Current is #{time}"

Thanks for your help!

A: 

Your t1 and time variables will not change. Time.now gives you a snapshot of what the current time is, but as time advances, previous variables which were assigned the value of Time.now will still have the same value as when they were set. Putting the time value inside a Hash will make no difference, whatsoever.

If you want to check the time later, you will have to get Time.now again.

t1 = Time.now
# ... time passes
t2 = Time.now

# Now you can compare t2 to t1 to see how much time elapsed.
Daniel Vandersluis
I guess time was a poor choice on my part. What I'm trying to do is, I parse out the time stamp of a file in my file system. I keep checking till it changes and when it does I call a different program. Not sure how to keep the original value on the next check for comparison purposes
rahrahruby
is it a stand alone program or is it on rails ?
kriss
A: 

Why convert to a string? You are introducing errors, as the time 10:05:02 will convert to "1052" with your code.

Instead, store the time object directly:

timestamps = {}
timestamps['old'] = Time.now
... more code ...
timestamps['new'] = Time.now

puts "Old time is: " + timestamps['old'].to_s
puts "New time is: " + timestamps['new'].to_s

If you want to compare the timestamps, you can use the spaceship operator like:

timestamps['old'] <=> timestamps['new']
bta
A: 
last_filetime = nil
while true
  filetime = file.timestamp
  call_other_process if last_filetime and filetime != last_filetime
  last_filetime = filetime
  pause 10
end

Does this help?

clocKwize