# Re: Fuzzy Time (#99)

**URL:** <https://www.ruby-forum.com/t/re-fuzzy-time-99/74756>\
**Category:** Ruby\
**Created:** [November 7, 2006, 10:55am UTC](https://www.ruby-forum.com/t/re-fuzzy-time-99/74756 "2006-11-07T10:55:17Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![phrogz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/2acd7d/32.png) [@phrogz](https://www.ruby-forum.com/u/phrogz)\
**Post date:** [November 7, 2006, 10:55am UTC](https://www.ruby-forum.com/t/re-fuzzy-time-99/74756/1 "2006-11-07T10:55:17Z")

</div>

Following is my (very late, but short) submission.

I first attempted to be really tricky about the time distribution in a  
variety of ways (which I’ll mention in the Summary), but found that the  
following code gave pretty good results (which you’ll see in the  
upcoming results email).

class Time  
def round\_to( seconds )  
seconds = seconds.round  
Time.at( self.to\_i / seconds \* seconds )  
end  
end

class FuzzyTime  
FIVE\_MINS = 5 \* 60  
TEN\_MINS = 10 \* 60  
attr\_reader :actual  
def initialize( start\_time=Time.new )  
@last\_fuzzy = @actual = @fuzzy = start\_time  
end

def update  
now = Time.new  
elapsed = now - ( @last\_update || now )  
advance( elapsed )  
@last\_update = now  
end

def advance( seconds\_forward )  
@actual += seconds\_forward

```
# Randomly move forward, centered around the desired seconds
@fuzzy += seconds_forward * 2 if rand < 0.5

# Ensure the fuzzy time is within legal bounds
overshoot = @fuzzy - @actual
if overshoot > FIVE_MINS
  @fuzzy = @actual + FIVE_MINS
elsif overshoot < -FIVE_MINS
  @fuzzy = @actual - FIVE_MINS
end

# Ensure that the fuzzy time is not less than the last *displayed*
if @fuzzy.round_to( TEN_MINS ) < @last_fuzzy.round_to( TEN_MINS )
  if $DEBUG
    puts "It is #{@actual.short}; " +
       "I wanted to show #{@fuzzy.short} (#{@fuzzy.to_fuzzy})," +
       " but I last showed " +
       "#{@last_fuzzy.short} (#{@last_fuzzy.to_fuzzy})"
  end
  @fuzzy = @last_fuzzy
end

```

end

def to\_s  
# only record the last _displayed_ time, to allow backtracking  
# as often as possible  
@last\_fuzzy = @fuzzy  
s = @fuzzy.strftime("%H:%M")  
s[4] = “~”  
s  
end

end
