How to Find the Day of the Week in Ruby
In this article, you will learn how to find the day of the week in Ruby.
Finding the day of the week
In Ruby, you can use the Date class from the standard library to find the day of the week. Here’s an example:
require 'date' # create a new Date object for January 1, 2020 date = Date.new(2020, 1, 1) # get the day of the week as an integer (0-6, where 0 is Sunday) day_of_week = date.wday # convert the integer to the name of the day day_name = Date::DAYNAMES[day_of_week] puts day_name #=> "Wednesday"
In this example, we first require the date library. Then, we create a new Date object for January 1, 2020 using the Date.new method. Next, we use the wday method to get the day of the week as an integer, where 0 is Sunday and 6 is Saturday. Finally, we use the DAYNAMES constant to convert the integer to the name of the day.
You can use this method to find the day of the week for any date by changing the arguments to the Date.new method.