Search code examples
rubyinterpolationstrptime

How can I execute strptime within a string using Ruby?


I have the following code:

line_item_interpolated = String.interpolate {line_item}
output_line = output_line + line_item_interpolated

It works fine for a case where: line_item = #{index}: #{item["value"]["time_string"]} for example.

But, if item['value']['time_string'] = '1453494900'for example, but I wanted that epoch time to be displayed as a formatted date using strptime, how would I do so by only setting the value for the string line_item

Where puts line_item_interpolated would print out a date, instead of the epoch-time above.


Solution

  • line_item = #{index}: #{Time.at(item["value"]["time_string"]})
    

    You can use Time#at:

    Time.at(1453494900)
    #=> 2016-01-22 21:35:00 +0100