What is wday attribute in Ruby?

Overview

In Ruby, the wday attribute is used to get the day of the week. It returns an integer value that represents the day of the week, from 0 to 6. Here 0 represents Sunday.

Syntax

time_obj.wday
Syntax to get the week day in Ruby

Return value

This attribute returns an integer value that represents the day of the week of a particular time object.

Example

# create time objects
time_now = Time.now # current time
time_five_hours = Time.at(946702800)
time_year_2021 = Time.new(2021)
def get_weekday(time_obj)
case time_obj.wday
when 0
puts "#{time_obj} is Sunday"
when 1
puts "#{time_obj} is Monday"
when 2
puts "#{time_obj} is Tuesday"
when 3
puts "#{time_obj} is Wednesday"
when 4
puts "#{time_obj} is Thursday"
when 5
puts "#{time_obj} is Friday"
when 6
puts "#{time_obj} is Saturday"
else
puts "error!"
end
end
get_weekday(time_now)
get_weekday(time_five_hours)
get_weekday(time_year_2021)

Explanation

  • Lines 2 to 4: We create some time objects using the Time.now attribute and Time.at() and Time.new() methods.
  • Line 6: We create a function get_weekday(), which takes a single parameter. It uses the Ruby case to check the weekday and prints the result.
  • Line 7: We use the wday attribute with case.
  • Lines 27 to 29: We call the get_weekday() function we created and pass in the time objects we created in lines 2 to 4.

Free Resources