Hi I want to form an array of next 7 days from today, Example: Suppose today is Sunday so result should be
["Sunday","Monday","Tuesday",'Wednesday","Thursday","Friday","Saturday"]
Here's a nice little one liner to do what you want.
(0..6).map{ |n| (Date.today+n).strftime("%A")}
Assuming today is Saturday, that will produce:
["Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
Quick explanation of each part:
(0..6)
creates an array of numbers: [0, 1, 2, 3, 4, 5, 6]
.
.map { |n| ... }
is a function called on the above array that takes each element in one at a time as n
.
(Date.today+n)
is an object that represents today's day (based on your system clock). It lets you add a number to it to offset the date, which creates a new object.
And finally .strftime("%A")}
is called on the offset date object to produce a string from the date object. The "%A"
is a format directive for string day of the week.
Using Ruby on Rails you do like that:
today = DateTime.now
(today..(today + 7.days)).map { |date| date.strftime("%A") }
=> ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
You will controll next days size modifying 7.days
part.
Answer supported from this Q&A
require 'date'
Date::DAYNAMES.rotate(Date.today.wday)
#=> ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
# "Friday", "Saturday"]
because Date.today.wday #=> 0
(Sunday). If today were Tuesday, Date.today.wday #=> 2
, so
Date::DAYNAMES.rotate(2)
#=> ["Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
# "Sunday", "Monday"]
See Array#rotate.
Code
require 'date'
p (Date.today..Date.today+7).map{|d|d.strftime("%A")}
Output
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With