Reputation: 2653
In my ruby code I want to display all the months name of last 1 year. For example current date is "April 2013"
then I want to display all months name from "May 2012"
to "April 2013"
such as ["May", "June", .., "April"]
. What is the best idea for this?
I tried:
<%= (1.year.ago.to_date.strftime("%B")..Date.today.strftime("%B")).map %> { |a| a } %>
But it gives: ["April"]
.
Upvotes: 3
Views: 1529
Reputation: 43298
In Rails you can do something like this:
<% 11.downto(0) do |i| %>
<%= i.months.ago.strftime("%B %Y") %>
<% end %>
Upvotes: 7
Reputation: 121000
Just out of curiosity, there is not wide-known nifty shift
operator on Date
:
(-12..0).inject([]) {
|agg, v| agg << Date::MONTHNAMES[(Date.today << v).month]
}
or, even simplier:
(-12..0).map { |v| Date::MONTHNAMES[(Date.today << v).month] }
Upvotes: 3
Reputation: 9008
(0..11).map do |month|
(11.months.ago + month.months).strftime("%B %Y")
end
Upvotes: 3
Reputation: 67850
11.downto(0).map { |m| m.months.ago.strftime("%B %Y") }
#=> ["May 2012", "June 2012", ..., "March 2013", "April 2013"]
Upvotes: 5
Reputation: 8333
Try this:
(0..11).each { |i|
month = (Date.today.month + i) % 12 + 1;
puts Date.new(Date.today.year - 1 + (month < Date.today.month ? 0 : 1), month).strftime("%B %Y")
}
Upvotes: 1