0

I want to list all weeknumbers together with year. This is what I have:

start # 2012-05-10
ende # 2013-06-20

while start < ende
   weeks << start.cweek
   start += 1.week
end

List all weeknumbers:

@kws.each do |w|
    w 
end

I need some inspiration how to assign the corresponding year to each weeknumber.. So that I get 22 / 2012 23 / 2012 etc..

Thanks for help..

Werner
  • 81
  • 2
  • 10

3 Answers3

0

Create a hash instead with key as a year and value as an array of week numbers

start # 2012-05-10
ende # 2013-06-20
weeks ={}
while start < ende
   weeks[start.year] = [] unless weeks[start.year]
   weeks[start.year] << start.cweek
   start += 1.week
end

p weeks

and you get o/p

 => {2012=>[19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 
 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52], 
2013=>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24]} 
Salil
  • 46,566
  • 21
  • 122
  • 156
0

When in your while loop, you can also store the year, and one easy way is just as an array of arrays.

Then in your each loop later you can get access to both:

start = Date.new( 2012, 5, 10 )
ende = Date.new( 2013, 6, 20 )

weeks = []
while start < ende
  weeks << [start.cweek, start.year]  # <-- enhanced
  start += 1.week
end

weeks.each do |w,y|   # <-- take two arguments in the block
  puts "#{w} / #{y}"  #     and print them both out
end

Results:

=> 
19 / 2012
20 / 2012
21 / 2012
22 / 2012
23 / 2012
24 / 2012
25 / 2012
...
22 / 2013
23 / 2013
24 / 2013
Nick B
  • 7,639
  • 2
  • 32
  • 28
-3
(10.weeks.ago.to_date..Date.today.to_date).map(&:beginning_of_week).uniq
Adriaan
  • 17,741
  • 7
  • 42
  • 75
Alex Yusupov
  • 1,001
  • 1
  • 9
  • 16
  • 2
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Jan 11 '23 at 07:17