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 objectstime_now = Time.now # current timetime_five_hours = Time.at(946702800)time_year_2021 = Time.new(2021)def get_weekday(time_obj)case time_obj.wdaywhen 0puts "#{time_obj} is Sunday"when 1puts "#{time_obj} is Monday"when 2puts "#{time_obj} is Tuesday"when 3puts "#{time_obj} is Wednesday"when 4puts "#{time_obj} is Thursday"when 5puts "#{time_obj} is Friday"when 6puts "#{time_obj} is Saturday"elseputs "error!"endendget_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.nowattribute andTime.at()andTime.new()methods. - Line 6: We create a function
get_weekday(), which takes a single parameter. It uses the Rubycaseto check the weekday and prints the result. - Line 7: We use the
wdayattribute withcase. - 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.