Created
September 14, 2018 06:35
-
-
Save axtutuu/de8fbb12ced1fa087f8b264c9ca1e36c to your computer and use it in GitHub Desktop.
Ruby Calendar
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'date' | |
| ## カレンダー出力 | |
| class Calender | |
| def initialize year, month | |
| @beginning_of_day = Date.new(year, month, 1) | |
| end | |
| # @example | |
| # 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 | |
| # ... | |
| def render | |
| ws = weeks | |
| result = ws.map do |w| | |
| w.map { |date| date.nil? ? ' ' : date.strftime(' %e') }.join(' ') | |
| end | |
| result = result.unshift(head) | |
| result.join("\n") | |
| end | |
| private | |
| # @example | |
| # [ | |
| # Date, Date, Date, ... | |
| # ] | |
| def dates | |
| end_of_day = @beginning_of_day.next_month.prev_day | |
| (@beginning_of_day..end_of_day).to_a | |
| end | |
| # @example | |
| # [ | |
| # [nil, nil, 1, 2, 3, 4, 5] | |
| # [6, 7, 8, 9, 10, 11, 12] | |
| # ... | |
| # ] | |
| def weeks | |
| ds = dates | |
| wdays = ds.first.wday.times.map { |i| nil } | |
| wdays.concat(ds).each_slice(7).to_a | |
| end | |
| def head | |
| "SUN MON TUE WED THU FRI SAT" | |
| end | |
| end | |
| p 'Input Year' | |
| year = gets.chomp | |
| p 'Input Month' | |
| month = gets.chomp | |
| c = Calender.new(year.to_i, month.to_i) | |
| puts c.render |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment