如何使用Ruby查找滚动年份的所有周?

时间:2014-08-04 22:24:24

标签: ruby

如何使用Ruby查找在当前日期之前的最后一个星期一结束的滚动年份中每周星期一的日期,然后创建一个散列,其中每个键都是星期几,每个值都为0 ?

4 个答案:

答案 0 :(得分:2)

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的更正和建议......(两次!)

答案 1 :(得分:2)

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

答案 2 :(得分:1)

你的第一个问题。

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)更改为{{1} })。

每个星期一结束的滚动年度将有53个星期一。因此,具有这些星期一的键的散列将如下:

(today.wday.zero?)

答案 3 :(得分: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]}]