Looping through weeks of the year in Ruby (Sinatra

2019-07-26 21:25发布

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?

3条回答
手持菜刀,她持情操
2楼-- · 2019-07-26 22:05

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楼-- · 2019-07-26 22:07
(1..52).each do |week|
   # find user that has reserved this week - and create a textbox
end
查看更多
相关推荐>>
4楼-- · 2019-07-26 22:16

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
查看更多
登录 后发表回答