每个月用日期对象迭代 [英] Iterate every month with date objects
问题描述
我已经添加了以下方法到Date类:
class Date
def all_months_until to
from = self
from,to = to,from if from>到
m = Date.new from.year,from.month
result = []
while m <= to
result<< m
m>> = 1
结束
结果
结束
结束
您可以使用它:
>> t = Date.today
=> #< Date:2009-11-12(4910295 / 2,0,2299161)>
>> t.all_months_until(t + 100)
=> [#< Date:2009-11-01(4910273 / 2,0,2299161)>#< Date:2009-12-01(4910333 / 2,0,2299161)>#< Date: 2010-01-01(4910395 / 2,0,2299161)><日期:2010-02-01(4910457 / 2,0,2299161)>]
好的,所以更多的rubyish方法IMHO将是一些东西:
code> class Month< Date
def succ
self>> 1
end
end
和
>> t = Month.today
=> #< Month:2009-11-13(4910297 / 2,0,2299161)>
>> (t..t + 100).to_a
=> [#< Month:2009-11-13(4910297 / 2,0,2299161)>#< Month:2009-12-13(4910357 / 2,0,2299161)>#< Month: 2010-01-13(4910419 / 2,0,2299161)>#< Month:2010-02-13(4910481 / 2,0,2299161)>]
但是,您需要小心使用月的第一天(或在月份实施此类逻辑)...
So I have two ruby Date objects, and I want to iterate them every month. For example if I have Date.new(2008, 12) and Date.new(2009, 3), it would yield me 2008-12, 2009-1, 2009-2, 2009-3 (as Date objects of course). I tried using range, but it yields every day. I saw step method for Date however it only allows me to pass number of days (and each month has different number of those). Anyone have any ideas?
I have added following method to Date class:
class Date
def all_months_until to
from = self
from, to = to, from if from > to
m = Date.new from.year, from.month
result = []
while m <= to
result << m
m >>= 1
end
result
end
end
You use it like:
>> t = Date.today
=> #<Date: 2009-11-12 (4910295/2,0,2299161)>
>> t.all_months_until(t+100)
=> [#<Date: 2009-11-01 (4910273/2,0,2299161)>, #<Date: 2009-12-01 (4910333/2,0,2299161)>, #<Date: 2010-01-01 (4910395/2,0,2299161)>, #<Date: 2010-02-01 (4910457/2,0,2299161)>]
Ok, so, more rubyish approach IMHO would be something along:
class Month<Date
def succ
self >> 1
end
end
and
>> t = Month.today
=> #<Month: 2009-11-13 (4910297/2,0,2299161)>
>> (t..t+100).to_a
=> [#<Month: 2009-11-13 (4910297/2,0,2299161)>, #<Month: 2009-12-13 (4910357/2,0,2299161)>, #<Month: 2010-01-13 (4910419/2,0,2299161)>, #<Month: 2010-02-13 (4910481/2,0,2299161)>]
But you would need to be careful to use first days of month (or implement such logic in Month)...
这篇关于每个月用日期对象迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!