I am reviewing the drill to strengthen my logical thinking. As a beginner, I would appreciate it if you could let me know if you have any questions.
Write the code to display today's day of the week using the Date class. However, only if it is Friday, please change the displayed contents as follows.
(Output contents) "Today is Monday" "Today is Friday !!!"
ruby.rb
require "date" #①
day = Date.today.wday #②
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] #③
if day == 5 #④
puts "today#{days[day]}That's it! !! !!"
else
puts "today#{days[day]}"
end
(1) Before using the Date class, you need to call the Date class from the Ruby library. The require method is used for this purpose.
(2) The typical acquisition method of the Date class instance (object) is the today method. It will get today's date. And since we want to get the day of the week this time, add the wday method. The return value of the wday method is a number from 0 to 6, and the day of the week is set to an integer from 0 (Sunday) to 6 (Saturday) to get the value. In other words, at the same time as creating an instance with Date.today and getting today's date, wday also gets the day of the week numerically and assigns it to the variable day.
(3) Since the return value of wday is a numerical value, it is necessary to specify the format for displaying the day of the week. Define in order by setting 0 to Sunday according to wday. You're ready to go!
④ Add a conditional bifurcation on Friday. If the conditional expression is false, it will move to the next conditional expression, so let's specify the condition for Friday first.
that's all!
Recommended Posts