What is time.to_s in Ruby?
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 objectstime_now = Time.now # current timetime_five_hours = Time.at(946702800)time_year_2021 = Time.new(2021)# get time in string# and print resultsputs time_now.to_sputs time_five_hours.to_sputs 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.nowattribute. -
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_sattribute on the time objects we created previously, and finally printed their results.