如何使用Ruby查找滚动年中每周的星期一的日期,该日期在当前日期前的最后一个星期一结束,然后创建一个哈希,其中每个键都是星期的日期,每个值都是0?
require 'date'
创建一个空散列:
hash = {}
计算上周一的天数:
days_to_previous_monday = Date.today.wday - 1
days_to_previous_monday = 6 if days_to_previous_monday < 0
上周一获取:
date = Date.today - days_to_previous_monday
构建53个星期一的散列:
53.times { hash[date] = 0; date -= 7 }
按升序对哈希进行排序:
hash.sort.to_h
编辑-包括Cary Swoveland的更正和建议。。(两次!(
require 'active_support/core_ext/date' #gem install activesupport
today = Date.today
p today #=>Mon, 04 Aug 2014
prev_day = today.days_ago(1)
p prev_day #=>Sun, 03 Aug 2014
prev_monday = prev_day.beginning_of_week(:monday)
p prev_monday #=> Mon, 28 Jul 2014
p prev_monday.prev_week #=>Mon, 21 Jul 2014
所以你可以这样做:
prev_monday = today.beginning_of_week(:monday) #If today is Monday, then returns today.
52.downto(0).each do |i|
p prev_monday.weeks_ago(i)
end
--output:--
Mon, 05 Aug 2013
Mon, 12 Aug 2013
Mon, 19 Aug 2013
...
...
...
Mon, 21 Jul 2014
Mon, 28 Jul 2014
Mon, 04 Aug 2014
散列可以这样构造:
data = ['a', 'b', 'c']
h = Hash[
data.zip([0] * data.length)
]
p h
--output:--
{"a"=>0, "b"=>0, "c"=>0}
但也许你只是想要一套:
require 'set'
data = ['a', 'b', 'c']
s = Set.new(data)
puts 'yes' if s.include?('b') #=> yes
您的第一个问题。
require 'date'
today = Date.today
prev_monday = today - ((today.wday <= 1) ? today.wday + 6 : today.wday - 1)
#<Date: 2014-07-28 ((2456867j,0s,0n),+0s,2299161j)>
我假设,如果今天是星期一(按原样(,那么您需要一周前的今天(不是今天的日期,但如果需要今天的日期则只需将(today.wday <= 1)
更改为(today.wday.zero?)
(。
每一个星期一结束的滚动年度将有53个星期一。因此,这些星期一的密钥散列如下:
52.downto(0).map { |i| [prev_monday - i*7, 0] }.to_h
#=> {#<Date: 2013-07-29 ((2456503j,0s,0n),+0s,2299161j)>=>0,
# #<Date: 2013-08-05 ((2456510j,0s,0n),+0s,2299161j)>=>0,
...
# #<Date: 2014-07-28 ((2456867j,0s,0n),+0s,2299161j)>=>0}
您可以尝试以下操作:
require 'date'
# we're explicit so it's easier to see what our "magic values" are doing
MONDAY = 1
# today isn't valid so our starting point is yesterday
yesterday = Date.today - 1
# we find out how many days of adjustment we need
offset = (yesterday - MONDAY).wday % 7
# map the results over 52 weeks
h = Hash[(0..51).map{|week| [yesterday - (week * 7 + offset), 0]}]