不妨定义一个类,实现 succ,<=> 方法,然后就可以用 Range 了:
class Ym
include Comparable
attr_accessor :year, :month
def initialize(year, month)
@year, @month = year, month
end
def succ
yyy, mmm = @month == 12 ? [@year + 1, 1] : [@year, @month + 1]
Ym.new(yyy, mmm)
end
def <=>(other)
(@year * 12 + @month) <=> (other.year * 12 + other.month)
end
def to_s
sprintf "%4d-%02d", @year, @month
end
end
使用:
(Ym.new(2008, 9)..Ym.new(2009, 8)).each do |ym|
puts ym
end
结果:
2008-09
2008-10
2008-11
2008-12
2009-01
2009-02
2009-03
2009-04
2009-05
2009-06
2009-07
2009-08