cyclingLinguist
cyclingLinguist

Reputation: 354

Why do my Time objects never get evaluated as equal in Ruby?

@dfa = Time.new
@type_me = gets
@i = 0
def type
  pause_duration = 2
  start_time = Time.new
  until Time.new == start_time + pause_duration
  puts "#{start_time + pause_duration} || #{Time.new}"
  end
  print @type_me[@i]
  @i += 1
  type
end

type

Why isn't Time.new ever equal to start_time + pause_duration?

Upvotes: 1

Views: 239

Answers (2)

sawa
sawa

Reputation: 168101

It is not that they are never equal. It is that it is very rare that they become equal. The loop takes time for each iteration. You are only comparing times with that increment, which does not necessarily add up to exactly 2.0 seconds at any point.

Upvotes: 1

pguardiario
pguardiario

Reputation: 54984

You're just not likely to get them with the same microsecond precision in the loop. Use >= instead.

Upvotes: 1

Related Questions