gpt4 book ai didi

ruby-on-rails - 在 Rails 中获取最近 X 个月的名称

转载 作者:太空宇宙 更新时间:2023-11-03 17:14:31 26 4
gpt4 key购买 nike

我正在尝试获取过去 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

最佳答案

基于 Olives' answer 构建的略显丑陋的版本,但不需要在每个月查找日期,速度大约快 31 倍:

current_month = Date.today.month

month_names = 6.downto(1).map { |n| DateTime::MONTHNAMES.drop(1)[(current_month - n) % 12] }

current_month 为 4 时的输出(测试 12 月-1 月的翻转):

["November", "December", "January", "February", "March", "April"] 

基准:

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>

与清洁版相比:

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>

关于ruby-on-rails - 在 Rails 中获取最近 X 个月的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38510701/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com