Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

string
ruby
communitycreator

What is time.to_s 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

The to_s attribute is a Ruby attribute that is invoked by a time object. It returns the string representation of the time object.

Syntax

timeObj.to_s
Syntax For getting String Representation of Time

Return value

The string representation of the time object timeObj is returned.

Code example

# create time objects
time_now = Time.now # current time
time_five_hours = Time.at(946702800)
time_year_2021 = Time.new(2021)
# get time in string
# and print results
puts time_now.to_s
puts time_five_hours.to_s
puts time_year_2021.to_s
Get Time Object in String

Explanation

  • Line 2: We created a time object which is the time now or the current system time using the Time.now attribute.

  • Line 3: We also created a time object by passing the number of seconds since the Unix Epoch to the Time.at() attribute.

  • Line 4: The Time.new() attribute was used to create a time object by passing the year to it.

  • Line 7-9: We invoked the to_s attribute on the time objects we created previously, and finally printed their results.

RELATED TAGS

string
ruby
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