Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

How to check if two time objects are the same in Ruby

okwudili onyejiaku

Overview

We can check whether or not two Time objects are the same using the eq()? method. It returns true if two Time objects have the same seconds. Otherwise, false is returned.

Syntax

t.eql?(other_t)
Check if Two Time Objects are The Same in Ruby

Parameters

t: This is a time instance that we want to compare with another time instance or object.

other_t: This is the other time object or instance we want to compare with t.

Return value

A boolean value is returned. true is returned if the seconds of the t and other_t are the same.

Code

# create time objects 
t1 = Time.now
t2 = Time.new(2023)
t3 = Time.new(946702800)
t4 = Time.new(946702800)
# compare
a = t1.eql?(t2)
b = t2.eql?(t3)
c = t3.eql?(t4)

# print results
puts a  # false
puts b  # false
puts c  # true
Compare Time Values in Ruby

Explanation

  • Line 1: We create a time object using the Time.now method.
  • Line 2: We also create a time object— this time with Time.new().
  • Line 3 and 4: We use the Time.new() method to create two time objects with the same number of seconds.
  • Line 7: We compare time objects t1 and t2.
  • Line 8: We compare time objects t2 and t3.
  • Line 9: We finally compare time objects t3 and t4.
  • Line 12-14: We print the results.

Only line 9 returns true when the code is run because t3 and t4 both have the same number of seconds.

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring