Home>

I want to create a program that calls the calendar month with OptionParser specified with -y, -m.

Error message

I want to call it by specifying year and month, but I'm at a loss as to how to specify it.
Could anyone please professor?

Source code
require "date"
require "optparse"
def calender_month (year: Date.today.year, month: Date.today.month)
        firstday = Date.new (year, month, 1)
        lastday = Date.new (year, month, -1)
        first_wday = firstday.wday
        lastday_date = lastday.day
        puts firstday.strftime ("% m month% Y"). center (20)
        puts "Sun Mon Tue Wed Thu Fri Sat"
        wday = firstday.wday
        print "" * wday
        days = (1..lastday_date) .map {| n | n.to_s.rjust (2)}
        days = Array.new (first_wday, '') .push (days) .flatten.each_slice (7) .to_a
        days.each do | week |
            puts week.join ('')
        end
        print "\ n"
end

I checked how to use OptionParser, but I didn't understand it.

Supplemental information (FW/tool version etc.)

Ruby2.6.5

  • Answer # 1

    I wrote while referring to the document. It might work with the following code

    def option_parse
      options = {}
      OptionParser.new do | opts |
        opts.on ('-y', '--year YEAR') do | v |
          options [: year] = v.to_i
        end
        opts.on ('-m', '--month MONTH') do | v |
          options [: month] = v.to_i
        end
      end.parse!
      options
    end
    # Pass the parsed value to the function
    calender_month (** option_parse)
    ruby ​​main.rb --year 2019 --month 12
    # =>
          December 2019
    Sunday Monday Tuesday Wednesday Thursday Friday Saturday
     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

    I hope you find something helpful

    Link

    Class: OptionParser (Ruby 2.6.5)

Trends