Search code examples
ruby-on-railsweek-number

Rails array with weeks and year


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..


Solution

  • 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