I know how to achieve this, but it doesn’t seem like the ruby way of doing it.
I have a hash of days in week:
DAYS = {
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
6 => "Saturday",
7 => "Sunday"}
(there is probably some rails helper for this, but I’ve implemented it the fastest way I could think of)
Now I would like to create an array where the first element is today, and the other days should remain ordered.
Here’s this array
def day_keys
# proper sorting of days, start with today and then continue
day_array = (1..7).to_a
loop do
break if day_array.first == Time.now.wday
day_array.rotate!
end
day_array
end
It’s Friday today, so it returns [5,6,7,1,2,3,4]. After this I map the values from this array with the keys from the DAYS hash to find the day names.
Solution seems pretty rough to me, so I would like to hear some ideas on how to implement this. I’ve spent some time looking at Array#cycle and Enumerable#inject but nothing seems to fit my needs.
How about:
((Time.now.wday)..(Time.now.wday+6)).collect{|i| ((i-1) % 7) +1}If you are in rails, you have a few more helpers. This yields an array of Dates:
And if you want the day name, it’s just a slight modification