7

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"]
Rajagopalan
  • 5,465
  • 2
  • 11
  • 29
Puja Garg
  • 251
  • 3
  • 11

4 Answers4

7

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.

jcdl
  • 680
  • 1
  • 5
  • 16
7
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.

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
6

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

Rafael Gomes Francisco
  • 2,193
  • 1
  • 15
  • 16
1

Code

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

Output

["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
Rajagopalan
  • 5,465
  • 2
  • 11
  • 29