How to check if two time objects are the same in Ruby
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 objectst1 = Time.nowt2 = Time.new(2023)t3 = Time.new(946702800)t4 = Time.new(946702800)# comparea = t1.eql?(t2)b = t2.eql?(t3)c = t3.eql?(t4)# print resultsputs a # falseputs b # falseputs c # true
Explanation
- Line 1: We create a time object using the
Time.nowmethod. - 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
t1andt2. - Line 8: We compare time objects
t2andt3. - Line 9: We finally compare time objects
t3andt4. - 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.