Calendar creation problem (fun Ruby practice problem)

Introduction

After learning "Introduction to Ruby for Professionals", commonly known as Cherry Book When I wanted to move my hands and put into practice what I input, I found an article by the author. "If you have trouble with output material !? I collected programming problems for Ruby beginners (10 questions in total)"

We are also solving other problems. First question: Calendar creation problem (fun Ruby practice problem) Second question: Karaoke machine creation problem Third question: Bingo card creation problem Fourth question: Bonus drink problem Fifth question: Phonebook creation problem

The first question listed here

This is an orthodox calendar creation problem described in "Fun Ruby". If you know the API of the Date class, you can write code with only basic programming knowledge.

Use the Date class to find the date and day of the week on the first and last day of the month, and display the calendar in the following format:

The goal is to make it look like this

     May 2020      
Su Mo Tu We Th Fr Sa
                1  2
 3  4  5  6  7  8  9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31 

When I searched, I was able to find various answers, but my answer was like this.

require 'date'

  def monthly_calendar(this_day = Date.today) #Execution date
    #Extract the first day of the execution month
    first_day = Date.new(this_day.year,this_day.month,1)
    #Sunday of the first week of the month(Upper left on the calendar)Extract the date corresponding to
    start_day = first_day - first_day.strftime('%w').to_i

    # month year
    puts this_day.strftime('%B %Y').center(21)
    # weekdays
    puts "\sSu\sMo\sTu\sWe\sTh\sFr\sSa"
    # days
    while start_day.month <= first_day.month

      if start_day.month != first_day.month
        print "\s\s\s"
      elsif start_day.strftime('%u') == "6"
        print "\s" + start_day.strftime('%e') + "\n"
      else
        print "\s" + start_day.strftime('%e')
      end

      start_day += 1
    end

  end

puts monthly_calendar

I was able to display the calendar for that month even if I passed only the year and month as arguments.

puts monthly_calendar(Date.new(1995,8)) #Can be specified in any month
     August 1995     
 Su Mo Tu We Th Fr Sa
        1  2  3  4  5
  6  7  8  9 10 11 12
 13 14 15 16 17 18 19
 20 21 22 23 24 25 26
 27 28 29 30 31

It seems that the value is passed on the date <1995-08-01>.


Please let us know if there are any improvements.

Recommended Posts

Calendar creation problem (fun Ruby practice problem)
Ruby problem ⑦
I tried a calendar problem in Ruby
ruby search problem
[Ruby] FizzBuzz problem
ruby API problem
[Ruby] FizzBuzz problem
[Ruby] Ruby API problem
ruby API problem
Portfolio creation Ruby on Rails
Creating a calendar using Ruby
[Ruby] problem with if statement
Ruby deposit system, algorithm problem