What is time.to_r in Ruby?
Overview
to_r is a Ruby attribute that is invoked by a time object. It returns the value of a time object as a rational number of seconds since the Epoch.
Syntax
timeObj.to_r
Syntax to get number of seconds of time as rational number
Return value
What is returned is the value of the time object timeObj as a rational number of seconds since the Epoch.
Code
# create time objectst1 = Time.now # current timet2 = Time.at(946702800)t3 = Time.new(2021)# get seconds since unix epoch# as rational number# and print resultsputs t1.to_rputs t2.to_rputs t3.to_r
Explanation
- line 2-4: we created some time objects.
- line 9-11: the rational number of seconds of the time objects were gotten using the
to_rattribute and printed to the console.