God*_*a74 2 ruby ruby-on-rails
我正在尝试获取过去 6 个月的月份名称数组。我见过其他帖子讨论迭代和打印实际日期 7/1/16、7/2/16 等,但没有任何内容只涉及月份名称:
[“二月”、“三月”、“四月”、“五月”、“六月”、“七月”]
我正在尝试以下代码,但出现此错误:
@array = []
(6.months.ago..Time.now).each do |m|
@array.push(Date::MONTHNAMES[m])
end
TypeError: can't iterate from ActiveSupport::TimeWithZone
Run Code Online (Sandbox Code Playgroud)
一个稍微丑陋的版本,基于Olives 的答案,但不需要查找每个月的日期,并且速度大约快 31 倍:
current_month = Date.today.month
month_names = 6.downto(1).map { |n| DateTime::MONTHNAMES.drop(1)[(current_month - n) % 12] }
Run Code Online (Sandbox Code Playgroud)
为 4时输出current_month(测试 12 月-1 月翻转):
["November", "December", "January", "February", "March", "April"]
Run Code Online (Sandbox Code Playgroud)
基准:
Benchmark.measure do
10000.times do
current_month = Date.today.month
month_names = 6.downto(1).map { |n| DateTime::MONTHNAMES.drop(1)[(current_month - n) % 12] }
end
end
=> #<Benchmark::Tms:0x007fcfda4830d0 @label="", @real=0.12975036300485954, @cstime=0.0, @cutime=0.0, @stime=0.07000000000000006, @utime=0.06999999999999984, @total=0.1399999999999999>
Run Code Online (Sandbox Code Playgroud)
与干净版本相比:
Benchmark.measure do
10000.times do
5.downto(0).collect do |n|
Date::MONTHNAMES[n.months.ago.month]
end
end
end
=> #<Benchmark::Tms:0x007fcfdcbde9b8 @label="", @real=3.7730263769917656, @cstime=0.0, @cutime=0.0, @stime=0.04999999999999993, @utime=3.69, @total=3.7399999999999998>
Run Code Online (Sandbox Code Playgroud)