ruby哈希存储

时间:2010-08-18 21:50:59

标签: ruby

我想获取当前时间并将其存储在哈希中,然后当我再次检查时将当前时间与存储时间进行比较。

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

感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

您的t1time变量不会更改。 Time.now为您提供当前时间的快照,但随着时间的推移,分配了Time.now值的先前变量仍将具有与它们相同的值被设定了。将时间值放在哈希中将无论如何都没有区别。

如果您想稍后查看时间,则必须再次获取Time.now

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

# Now you can compare t2 to t1 to see how much time elapsed.

答案 1 :(得分:0)

为什么要转换为字符串?您正在引入错误,因为时间10:05:02将使用您的代码转换为“1052”。

相反,直接存储时间对象:

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

如果您想比较时间戳,可以使用太空船运营商,如:

timestamps['old'] <=> timestamps['new']

答案 2 :(得分:0)

last_filetime = nil
while true
  filetime = file.timestamp
  call_other_process if last_filetime and filetime != last_filetime
  last_filetime = filetime
  pause 10
end

这有帮助吗?