1.

Can you print the current day of the week in words such if the current day is Monday then it should print “Monday” in Ruby?

Answer»

Ruby is provided with default libraries in the form of classes, which will be accessible after installing ruby in your system. These libraries are referred to as Ruby Standard Library. Some of the libraries need to be invoked explicitly. ‘Date’ class is a library in ruby where you can get most of the actions related to date and make use of these to IMPLEMENT your REQUIREMENT. You need to load the ‘date’ module in file or IRB or console where you want to print the current day of the week.

The following example is in IRB,

Load ‘date’ class to get the current day of the week in ruby.

For example:

//----start CODE-------- > load ‘date’ >   Date.today.strftime("%A") => "Sunday" //----end code--------

From the above example, In the first line, we have loaded the ‘date’ library. Now you will have all the required classes and methods available for you in this IRB console. ‘Date’ is the class that we will be using to get the current day of the week. Date.today will give the current day information such as date, month and year. CALLING strftime method on the current day to FORMAT and get the desired output. In this case, You will use ‘%A’ to get the current day of the week which is ‘Sunday’. There are also many other options to format the date such as get the month in the letter, month in word, year in the letter, year in 4 digits, year in 2 digits, etc

Please refer to the following for more formatting options
Creating a new Time instance



Discussion

No Comment Found