I am trying to come up with an efficient method for truncating Ruby Time objects according to a given resolution.
class Time
def truncate resolution
t = to_a
case resolution
when :min
t[0] = 0
when :hour
t[0] = t[1] = 0
when :day
t[0] = t[1] = 0
t[2] = 1
when :month
t[0] = t[1] = 0
t[2] = t[3] = 1
when :week
t[0] = t[1] = 0
t[2] = 1
t[3] -= t[6] - 1
when :year
t[0] = t[1] = 0
t[2] = t[3] = t[4] = 1
end
Time.local *t
end
end
Does anyone know a faster version that achieves the same task?
Thanks to both of you. Since I don’t use Rails I copied the code to perform a performance benchmark.
Here are the results:
Seems like my first truncation version is still most efficient, except for the year case. There is a small quirk in the year for
truncateandtruncate3though. It is displayed asrather than
Any ideas why?