In message "[ruby-list:15284] Re: 年月を範囲でうまく扱うには?"
on 99/07/07, Yukihiko Eda <yuki-e / geocities.co.jp> writes:
>> 大した手間でもなさそうだし、年月のクラスを作っちゃうのは
>> どうでしょうか??
>
>ありがとうございます。さっそく試してみます。
10分くらいで書いたのでバグバグでした。
少しまともにしたのを送ります。
Month
Included modules
Comparable
Class methods
new(y,m)
creates new month oject for year y, month m
Methods
year
month
returns a integer
succ
returns its next month
<=>, <=, =>, <, >, ==
comparison methods between months
has?(date_or_time)
returns if Date or Time is in the month or not.
inspects
to_s
returns a human readable string
require "date"
class Month
include Comparable
Monthtag = [
"January","February","March","April", "May", "June","July",
"August", "September", "October", "November", "December"
]
def initialize(y, m)
unless y.kind_of?(Integer) && m.kind_of?(Integer) && 1..12 == m
raise ArgumentError.new
end
@t = y*12 + m - 1
end
def year
@t/12
end
def month
@t%12 + 1
end
def succ(n = 1)
t = @t + n
Month.new(t/12, t%12 + 1)
end
def <=>(o)
if o.kind_of?(Month)
@t <=> o.year*12 + o.month - 1
end
end
def has?(o)
if o.kind_of?(Date) or o.kind_of?(Time)
@t == o.year*12 + o.month - 1
end
end
def inspect
format("%04d-%02d", @t/12, @t%12 + 1)
end
def to_s
Monthtag[@t%12][0..2] + " #{@t/12}"
end
end
if __FILE__ == $0
mrange = Month.new(1997,1)..Month.new(1999,12)
today = Date.new(Time.now.year, Time.now.month)
now = Time.now
$\ = "\n"; $, = ", "
for i in mrange
print i, i.has?(today), i.has?(now)
end
end