distance_of_time_in_words
是偉大的,但有時它不夠精細。更精確distance_of_time_in_words
我需要一個函數來報告單詞中的確切時間距離。例如,上午7:50到10:10應該是「2小時20分鐘」的距離,而不是「大約2小時」或任何distance_of_time_in_words
會做的。
我的使用案例是報告火車時刻表,特別是一個特定的火車車程需要多長時間。
distance_of_time_in_words
是偉大的,但有時它不夠精細。更精確distance_of_time_in_words
我需要一個函數來報告單詞中的確切時間距離。例如,上午7:50到10:10應該是「2小時20分鐘」的距離,而不是「大約2小時」或任何distance_of_time_in_words
會做的。
我的使用案例是報告火車時刻表,特別是一個特定的火車車程需要多長時間。
def distance_of_time_in_hours_and_minutes(from_time, to_time)
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
distance_in_hours = (((to_time - from_time).abs)/3600).round
distance_in_minutes = ((((to_time - from_time).abs) % 3600)/60).round
difference_in_words = ''
difference_in_words << "#{distance_in_hours} #{distance_in_hours > 1 ? 'hours' : 'hour' } and " if distance_in_hours > 0
difference_in_words << "#{distance_in_minutes} #{distance_in_minutes == 1 ? 'minute' : 'minutes' }"
end
我會改行 個distance_in_hours =(((TO_TIME - FROM_TIME)。ABS)/ 3600).round 到 distance_in_hours =(((TO_TIME - FROM_TIME)。ABS)/ 3600).to_i 的輪將上舍入,使1.5小時看起來像2小時30分鐘 – theschmitzer 2010-08-06 20:35:02
上面的代碼混淆了我的Rubymine ......並且我不確定它實際上是否正確。我重建它,如下所示:
def distance_of_time_in_hours_and_minutes(from_time, to_time)
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
dist = to_time - from_time
minutes = (dist.abs/60).round
hours = minutes/60
minutes = minutes - (hours * 60)
words = dist <= 0 ? '' : '-'
words << "#{hours} #{hours > 1 ? 'hours' : 'hour' } and " if hours > 0
words << "#{minutes} #{minutes == 1 ? 'minute' : 'minutes' }"
end
下面是一些Rspec的針對上述:
describe "Distance of Time in Hours and Minutes" do
before do
@time1 = Time.utc(2010,"sep",7,14,15,3)
@time2 = @time1 + 28
@time3 = @time1 + 30
@time4 = @time1 + 60
@time5 = @time1 + 60*60
@time6 = @time1 + 60*60 + 60
@time7 = @time1 + 60*60 + 5*60
end
it "calculates time differences properly" do
distance_of_time_in_hours_and_minutes(@time1, @time1).should == "0 minutes"
distance_of_time_in_hours_and_minutes(@time1, @time2).should == "0 minutes"
distance_of_time_in_hours_and_minutes(@time1, @time3).should == "1 minute"
distance_of_time_in_hours_and_minutes(@time1, @time4).should == "1 minute"
distance_of_time_in_hours_and_minutes(@time1, @time5).should == "1 hour and 0 minutes"
distance_of_time_in_hours_and_minutes(@time1, @time6).should == "1 hour and 1 minute"
distance_of_time_in_hours_and_minutes(@time1, @time7).should == "1 hour and 5 minutes"
distance_of_time_in_hours_and_minutes(@time7, @time1).should == "-1 hour and 5 minutes"
distance_of_time_in_hours_and_minutes(@time3, @time1).should == "-1 minute"
end
end
(請注意,我在我的編碼環境,以避免NoMethodError誤差過的distance_of_time_in_miles
前插每次調用與helper
-
是不是這一行「words = dist <= 0? '':' - '「是錯誤的方法?如果dist是正數,則返回負號,而如果dist是負數,則可能會返回它。 – 2011-01-18 13:16:33
更新鏈接:https://github.com/radar/dotiw其實更好, – 2009-08-13 14:44:16