It is a function of the standard library of Ruby.
To use the Date class, write the following sentence.
require "date"
Then use the Date class
To get "Today's day of the week", write as follows.
day = Date.today.wday
wday is a method provided in the Date class that allows you to get the day of the week as an integer from 0 (Sunday) to 6 (Saturday).
For example, on Thursday, 4 is output!
I thought about how to output "Today is Thursday".
require "date"
day = Date.today.wday
if day == 0
puts "Today is sunday"
elsif day == 1
puts "Today is monday"
elsif day == 2
puts "Today is Tuesday"
elsif day == 3
puts "Today is wednesday"
elsif day == 4
puts "Today is thursday"
elsif day == 5
puts "Today is Friday! !! !!"
else
puts "Today is saturday"
end
The If statement is long, so it looks like it can be refactored.
The point is that the numbers are output,
It seems that the same result as above can be obtained by substituting the output number into the subscript using the array.
require "date"
day = Date.today.wday
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
puts "today#{days[day]}"
It is compactly organized.
If you use an If statement, it's better to use it when changing comments on a specific day of the week.
I can't write anything to shorten the code yet, so I'd like to remember it while doing it!
Recommended Posts