Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array of next 7 days name from today in ruby

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"]
like image 364
Puja Garg Avatar asked Jul 19 '20 03:07

Puja Garg


Video Answer


4 Answers

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.

like image 59
jcdl Avatar answered Oct 08 '22 07:10

jcdl


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

like image 41
Rafael Gomes Francisco Avatar answered Oct 08 '22 07:10

Rafael Gomes Francisco


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.

like image 29
Cary Swoveland Avatar answered Oct 08 '22 05:10

Cary Swoveland


Code

require 'date'
p (Date.today..Date.today+7).map{|d|d.strftime("%A")}

Output

["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
like image 34
Rajagopalan Avatar answered Oct 08 '22 05:10

Rajagopalan