由于您的问题已被诊断,我将限制我的答案以显示如何使用类Date。
代码
require 'date'
DAY_WIDTH = 4
def calendar(year, month)
title = "#{Date::MONTHNAMES[month]}, #{year}".center(7*DAY_WIDTH)
puts "\n#{title}"
Date::ABBR_DAYNAMES.each { |s| print s.rjust(DAY_WIDTH) }
puts
arr = [*[' ']*Date.new(year,month).wday, *1..days_in_month(year,month)]
arr.each_slice(7) { |week|
week.each { |d| print d.to_s.rjust(DAY_WIDTH) }; puts }
end
def days_in_month(year,month)
(((month==12) ? Date.new(year+1,1) : Date.new(year,month+1)) -
Date.new(year,month))
end
[编辑:他的回答here,@spickerman当月由此表达的天数:Date.new(year,month,-1).day
。 ?好,嗯]
例子
calendar(2015, 2)
February, 2015
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
calendar(2015, 4)
April, 2015
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
calendar(2016, 2)
February, 2016
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
说明
考虑第二个例子:
year = 2015
month = 4
首页打印标题:
title = "#{Date::MONTHNAMES[month]}, #{year}".center(7*DAY_WIDTH)
#=> "April, 2015".center(28)
#=> " April, 2015 "
puts "\n#{title}"
下一页打印周头的天:
Date::ABBR_DAYNAMES.each { |s| print s.rjust(DAY_WIDTH) }
#=> ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].each { |s|
#=> print s.rjust(4) }
# Sun Mon Tue Wed Thu Fri Sat
例如,"Sun".rjust(4)" #=> " Sun"
。
现在我们需要在每周打印日子。我已经做了两个步骤:首先创建一个数组天要打印,包括在第一周0-6
空间,然后打印每组七个要素:
arr = [*[' ']*Date.new(year,month).wday, *1..days_in_month(year,month)]
#=> arr = [*[' ']*3, *1..30]
#=> arr = [*[' ', ' ', ' '], *1..30]
#=> [" ", " ", " ", 1, 2,..., 30]
我们现在划分arr
成七组和打印每个:
arr.each_slice(7) { |week|
week.each { |d| print d.to_s.rjust(DAY_WIDTH) }; puts }
例如:
' '.to_s.d.to_s.rjust(4)
#=> ' '
10.to_s.rjust(4)
#=> ' 10'
在四月的天数,2015计算如下:
(((month==12) ? Date.new(year+1,1) : Date.new(year,month+1))-
Date.new(year,month))
#=> (((4==12) ? Date.new(2016,1) : Date.new(2015,5))-Date.new(2015,4)
#=> Date.new(2015,5) - Date.new(2015,4)
#=> #<Date: 2015-05-01 ((2457144j,0s,0n),+0s,2299161j)> -
#<Date: 2015-04-01 ((2457114j,0s,0n),+0s,2299161j)>
#=> (30/1), a rational number equal to 30
尼斯一个@CarySwoveland,你可能有兴趣在我的解决方案,我到OPS等问题提供:http://stackoverflow.com/a/29908459/2483313 – spickermann
@spickermann,感谢您的链接。有趣的阅读! –