I need to create an array like this
["January 2020, February 2020, March 2020, April 2020, May 2020, June 2020, and so on till last month]
With Date::MONTHNAMES, it enumerizes only the months but I don't find a way to add the years. Thank you,
CodePudding user response:
You can use map method.
month_names = Date::MONTHNAMES.compact.map{ |m| "#{m} #{Time.zone.now.year}" }
p month_names
#=> ["January 2021", "February 2021", "March 2021", "April 2021",
"May 2021", "June 2021", "July 2021", "August 2021", "September 2021",
"October 2021", "November 2021", "December 2021"]
CodePudding user response:
You can simply map it and add the current year, something like this Date::MONTHNAMES.compact.map{ |month| "#{month} #{Date.current.year}" }
CodePudding user response:
I would go with:
def month_names(year)
1.upto(12).map |month|
Date.new(year, month).strftime("%b %Y")
end
end
While this seems like overkill compared to simple string concatention you can easily swap out strftime
for the I18n module to localize it.
def month_names(year)
1.upto(12).map |month|
I18n.localize(Date.new(year, month), format: :long)
end
end
# config/locale/pirate.yml
pirate:
date:
formats:
long: "Aargh! it be the on the fair month of %m %Y"