如何比较红宝石的时间

Rob*_*dez 8 ruby time

我需要使用Time对象作为int(TimeObject.to_i)然后我需要将int转换回Time,以与原始Time进行比较.简短的例子

t1 = Time.now
t2 = Time.at(t1.to_i)
puts t1 == t2    # Says False
puts t1.eql?(t2) # Says False
Run Code Online (Sandbox Code Playgroud)

为什么这说错呢?当我同时打印时,objetcs显示同样的事情D:

puts t1                 #shows : 2012-01-06 16:01:53 -0300
puts t2                 #shows : 2012-01-06 16:01:53 -0300
puts t1.to_a.to_s       #shows : [ 53, 1, 16, 6, 1, 2012, 5, 6, true, "CLST"]      
puts t2.to_a.to_s       #shows : [ 53, 1, 16, 6, 1, 2012, 5, 6, true, "CLST"]      
Run Code Online (Sandbox Code Playgroud)

他们是同一件事D:但是当试图与==或eql进行比较时?说他们不同(抱歉我的英语不好)

Ser*_*sev 13

回答

t1 = Time.now
t2 = Time.at(t1.to_i)
t3 = Time.at(t1.to_i)
puts t1  # 2012-01-06 23:09:41 +0400
puts t2  # 2012-01-06 23:09:41 +0400
puts t3  # 2012-01-06 23:09:41 +0400

puts t1 == t2      # false
puts t1.equal?(t2) # false
puts t1.eql?(t2)   # false

puts t2.equal? t3  # false
puts t2.eql? t3    # true
puts t2 == t3      # true
Run Code Online (Sandbox Code Playgroud)

说明:

EQL?(other_time)

如果time和other_time都是具有相同秒和小数秒的Time对象,则返回true.

链接:时间#eql?

因此,显然,在执行时会丢失几分之一秒#to_i,然后恢复时间与原始时间不完全相同.但如果我们恢复两份,他们将是平等的.

人们可能会想,"嘿,让我们用#to_f吧!".但是,令人惊讶的是,结果是一样的!也许是因为舍入错误或浮点比较,不确定.

替代答案

不要将整数转换回时间进行比较.将原始时间转换为int而不是!

t1 = Time.now
t2 = Time.at(t1.to_i)

puts t1  # 2012-01-06 23:44:06 +0400
puts t2  # 2012-01-06 23:44:06 +0400

t1int, t2int = t1.to_i, t2.to_i

puts t1int == t2int           # true
puts t1int.equal?(t2int.to_i) # true
puts t1int.eql?(t2int)        # true
Run Code Online (Sandbox Code Playgroud)