Looping through weeks of the year in Ruby (Sinatra)

﹥>﹥吖頭↗ 提交于 2019-12-24 09:28:43

问题


I'm creating a very simple timeshare application using Sinatra and Datamapper. Every user in the application will have n reservations and for the time being each reservation runs from Monday to Sunday and there can only be one reservation per week.

Now I will need a view with a textbox (and label) for each week of the year where the users will put their name (through autocompletion or something) and thereby creating a reservation for that week. And if the week is reserved the name will of course be filled in the textbox (and disabled)

It would be something like

weeks.each do
  find user that has reserved this week - and create a textbox
end

So my question I guess is as simple - how do I loop through all weeks of a year in Ruby?

Or would it be a better solution to just loop 52 times and make an array for each user with the numbers of reserved weeks in it?


回答1:


(1..52).each do |week|
   # find user that has reserved this week - and create a textbox
end



回答2:


You should loop through this:

(Date.beginning_of_year.cweek...Date.today.end_of_year.cweek).each do |week|
  find user that has reserved this week - and create a textbox
end



回答3:


For others that might find this old question, like I did...

January 1 is sometimes week 53. December 31 is sometimes week 1. If you want to loop through all the weeks of the year, you must first decide if you want the first days of january, even when it could be the previous year's week 53.

To get the highest week-number in a year, you can always check december 28 (since ISO-weeks state that week 1 is the week with the first thursday).

If you don't care about the first days of january (might be fri-sun), you might do something like:

require 'date' # Already included in sinatra though

(1..Date.parse("#{year}-12-28").cweek).each do |week|
  puts week
end


来源:https://stackoverflow.com/questions/4019045/looping-through-weeks-of-the-year-in-ruby-sinatra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!