LoginSignup
10
8

More than 5 years have passed since last update.

カレンダー出力の練習

Last updated at Posted at 2015-02-20

問題

年と月を入力してカレンダーを出力する

こちらのサイトから引用

解答

calendar.rb
# 入力された年の月の1日の曜日を計算
# ツェラーの公式を使用
# year:入力された年
# month:入力された月
# d:日にち(今回は1で固定)
# 返り値:曜日(1:日 2:月 3:火 4:水 5:木 6:金 0:土)
def calc_day(year, month, d = 1)
  # 1月, 2月は前年の13月, 14月として計算 
  if month == 1 || month == 2
    month += 12
    year  -= 1
  end

  # ツェラーの公式用の数を求める
  h = year / 100
  y = year % 100
  m = month

  # 曜日計算
  (y + (y / 4) + (h / 4) - (2 * h) + ((13 * (m + 1)) / 5) + d) % 7
end

# うるう年かどうか判定するメソッド
# year:入力された年
# 返り値:うるう年ならtrue, 平年ならfalse
def leap_year_judge(year)
  case
  when (year % 400).zero?
    true
  when (year % 100).zero?
    false
  when (year % 4).zero?
    true
  else
    false 
  end
end

# 日にちを1日から描画
# year_date:1ヶ月の日にちが入った配列
# month:表示する月
# current_day:曜日
def print_date(year_date, month, current_day)
  (1..year_date[month]).each do |date|
    # 日にちを描画
    print format("%3d ", date)
    current_day += 1
    # 土曜にになったら改行
    if current_day % 7 == 0
      print "\n"
    end
  end
end

# カレンダーを表示
def show_calendar(year, month, day)
  # うるう年じゃない年の日数(後で参照しやすいように0月の0日を設定)
  year_days      = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  # うるう年の年の日数
  leap_year_days = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  # ツェラーの公式の曜日だと扱いにくいから日曜を0にする
  # 土曜は6
  day -= 1
  day += 7 if day < 0

  # うるう年判定
  # うるう年ならtrue, 平年ならfalse
  leap_year_flag = leap_year_judge(year)

  puts "カレンダーを表示します"
  puts "Sun Mon Tue Wed Thu Fri Sat"

  # 1日の位置を決める
  # 1日の曜日になるまでスペース表示
  day.times do
    print "    "
  end

  # うるう年かどうかで最終日が違ってくる(2月だけだけど…)
  if leap_year_flag
    # 日にちを表示
    print_date(leap_year_days, month, day)
  else
    print_date(year_days, month, day)
  end
end

# ===========================================
#                ここから開始
# ===========================================

puts "任意の年と月のカレンダーを表示します"

# 西暦を入力
print "西暦を入力してください : "
input_year = gets.to_i
# 月を入力
print "月を入力してください : "
input_month = gets.to_i

# 入力した年の月の曜日を計算
first_day = calc_day(input_year, input_month)

# カレンダーを描画
show_calendar(input_year, input_month, first_day)

結果

任意の年と月のカレンダーを表示します
西暦を入力してください : 2015
月を入力してください : 1
カレンダーを表示します
Sun Mon Tue Wed Thu Fri Sat
                  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 

参考

ツェラーの公式-wikipedia

10
8
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8