Trusted answers to developer questions

What is time.to_r in Ruby?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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 objects
t1 = Time.now # current time
t2 = Time.at(946702800)
t3 = Time.new(2021)
# get seconds since unix epoch
# as rational number
# and print results
puts t1.to_r
puts t2.to_r
puts 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_r attribute and printed to the console.

RELATED TAGS

ruby
rational
Did you find this helpful?