Ruby – Find Day Number – cwday Method – Examples & Explanation

cwday method is used to find the number of the day of a calendar week. Often it becomes necessary to find the number of the day of a calendar week like (1, 2, 3). This function provides the complete solution in getting the number of the day of a calendar week (1-7, Monday is 1). cwday is a part of Date library in Ruby.

Syntax of cwday Method in Ruby

The syntax of cwday Method in Ruby Language is:

Date.new(x).cwday 

 

Parameters of cwday Method in Ruby

x – Where x is any valid date object. This parameter is required.

 

Error Handling

If the x parameter is not a valid date type which is required to find out the number of the day from, the cwday method returns an error.

 

Return Value of cwday Method in Ruby

cwday method will return the number of the day of a calendar week (1-7, Monday is 1).

 

How to get the Week Day in Ruby with cwday Method?

# import date library
require 'date'
x = Date.new(2016,2,6).cwday
puts x

Output:
6

Use of cwday method / function in Ruby

# import date library
require 'date'
x = Date.new(2016,10,25).cwday
puts x

Output:
2

Get the Number of a Day with DateTime Method in Ruby

# import date library
require 'date'
x = DateTime.new(2016,11,20).cwday
puts x

Output:
7