What is the time.to_f method in Ruby?
Overview
In Ruby, the to_f method is used to return the value of a time object as a floating-point number of seconds since the
Syntax
timeObj.to_f
Syntax to get number of seconds of time as float
Parameters
This method takes no parameters. It is only invoked by a time object, which in our case is timeObj.
Return value
This method returns the value of the time object timeObj as a floating-point number of seconds since the Epoch.
Example
# create time objectst1 = Time.now # current timet2 = Time.at(946702800)t3 = Time.new(2021)# get seconds since unix epoch# in floating point# and print resultsputs t1.to_fputs t2.to_fputs t3.to_f
Explanation
- Line 2: We use the
Time.nowto method create a time object, which is the current time or the current system time . - Line 3: We create a time object by passing the number of seconds since the Unix Epoch to the
Time.at()method. - Line 4: We use the
Time.new()method to create a time object by passing the year2021to it. - Lines 9–11: We invoke the
to_fmethod on the time objects, and print the results.