ruby hash storing
I want to take the current time and store it in hash and then when I check it again comp开发者_如何学JAVAare 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!
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.
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']
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?
精彩评论