Trusted answers to developer questions

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

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

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
Did you find this helpful?