2011-10-18 16 views
2

我需要知道如何在軌道中做相對時間,但不是作爲一個句子,更像是我可以做到這一點(當我輸入像這樣的格式2008-08-05 23:48 :04 -0400)在軌道中使用和比較相對時間

if time_ago < 1 hour, 3 weeks, 1 day, etc. 
    execute me 
end 

回答

7

基本相對時間:

# If "time_ago" is more than 1 hour past the current time 
if time_ago < 1.hour.ago 
    execute_me 
end 


比較:

使用<,看是否time_ago1.hour.ago年齡大了,>,看是否time_ago1.hour.ago


結合時代更近,並用分數次:

您可以結合時間,作爲davidb提及,並且做到:

(1.day + 3.hours + 2500.seconds).ago 

你也可以做分數秒ds,如: 0.5.seconds.ago

沒有.milliseconds.ago,所以如果您需要毫秒精度,只需將其分解成小數秒。也就是說,1毫秒前的是:

0.001.seconds.ago 


.ago()一般:

.ago在幾乎任何數量年底將當作一個循環移位#of秒數。

您甚至可以使用分數在paranthesis:

(1/2.0).hour.ago # half hour ago 
(1/4.0).year.ago # quarter year ago 

注意:要使用的部分,無論是分子或分母必須是一個浮點數,否則紅寶石會自動施放答案的整數,甩掉你的數學。

3

你的意思是......喜歡這個?

if time_ago < Time.now-(1.days+1.hour+1.minute) 
    execute me 
end 
+0

你也可以寫爲'(1.days + 1.hour + 1.minute).ago' – jefflunt

+0

@davidb感謝,那是什麼,我需要 – Kevin

+0

@davidb你的工作,生病切換到normalocity的答案,因爲它更徹底,幫助其他人 – Kevin