Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

time
ruby
integer
communitycreator

What is the time.to_i method in Ruby?

okwudili onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

In Ruby, the to_i method is invoked by a time object. This method returns the value of a time object as an integer number of seconds since the Epoch.

Syntax

timeObj.to_i
Syntax to get the number of seconds of time as integer

Parameters

This method takes no parameters. It is only invoked by timeObj, which is a time object.

Return value

The time object timeObj returns an integer of seconds since the Epoch.

Code example

# create time objects
t1 = Time.now # current time
t2 = Time.at(946702800)
t3 = Time.new(2021)
# get seconds since unix epoch
# in integer
# and print results
puts t1.to_i
puts t2.to_i
puts t3.to_i
Get seconds of a time object in integer

Code explanation

  • Line 2: We create a time object, which is the time now or the current system time, using the Time.now method.
  • Line 3: We also 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 to it.
  • Lines 9–11: We invoke the to_i method on the time objects we created previously. Finally, we print their results.

RELATED TAGS

time
ruby
integer
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring