What is yday attribute in Ruby?

Overview

The yday attribute in Ruby is used to return the day of the year. There are 365 days (366 days for leap years) in a year. So, this method returns an integer that represents the day of the year, from 1 to 366.

Syntax

time_obj.yday
Syntax to get the year of the day in Ruby

Return value

This attribute returns an integer from 1 to 365 (366 for leap years).

Example

# create time objects
time_now = Time.now # current time
time_five_hours = Time.at(946702800)
time_year_2021 = Time.new(2021)
time_wednesday_1993 = Time.local(1993, 2, 24)
# call the yday method
# and print results
puts time_now.yday
puts time_five_hours.yday
puts time_year_2021.yday
puts time_wednesday_1993.yday

Explanation

  • Line 2: We create a time object using the Time.now attribute that returns the current time object.
  • Line 3: We use the Time.at() method to create a time object by passing the number of seconds since the UNIX epoch.
  • Line 4: We use the Time.new() method to create a new time object by passing it the year 2021.
  • Line 5: We use the Time.local() method to create a time object by passing in the year, month, and day of the month.
  • Lines 9 to 12: We call the yday attribute on the time objects we created and print their results to the console.