使用divmod
可以非常简洁地完成:
t = 270921
mm, ss = t.divmod(60) #=> [4515, 21]
hh, mm = mm.divmod(60) #=> [75, 15]
dd, hh = hh.divmod(24) #=> [3, 3]
puts "%d days, %d hours, %d minutes and %d seconds" % [dd, hh, mm, ss]
#=> 3 days, 3 hours, 15 minutes and 21 seconds
你可能会用collect
或inject
来创作,从而让它更加干涸,但当核心逻辑是三行时,这可能会有些过分.