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 EpochAn epoch is a date and time from which a computer measures system time. In ruby, Epoch is the number of seconds passed since since January 1, 1970..

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 objects
t1 = Time.now # current time
t2 = Time.at(946702800)
t3 = Time.new(2021)
# get seconds since unix epoch
# in floating point
# and print results
puts t1.to_f
puts t2.to_f
puts t3.to_f

Explanation

  • Line 2: We use the Time.now to 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 year 2021 to it.
  • Lines 9–11: We invoke the to_f method on the time objects, and print the results.

Free Resources