gpt4 book ai didi

ruby-on-rails - 如何使用 ruby​​ on rails 生成人类可读的时间范围

转载 作者:数据小太阳 更新时间:2023-10-29 06:27:23 25 4
gpt4 key购买 nike

我正在尝试找到生成以下输出的最佳方法

<name> job took 30 seconds
<name> job took 1 minute and 20 seconds
<name> job took 30 minutes and 1 second
<name> job took 3 hours and 2 minutes

我开始这段代码

def time_range_details
time = (self.created_at..self.updated_at).count
sync_time = case time
when 0..60 then "#{time} secs"
else "#{time/60} minunte(s) and #{time-min*60} seconds"
end
end

有没有更有效的方法呢?看起来 super 简单的东西有很多冗余代码。

另一个用途是:

<title> was posted 20 seconds ago
<title> was posted 2 hours ago

此代码类似,但我使用 Time.now:

def time_since_posted
time = (self.created_at..Time.now).count
...
...
end

最佳答案

如果你需要比 distance_of_time_in_words 更“精确”的东西,你可以按照这些行写一些东西:

def humanize(secs)
[[60, :seconds], [60, :minutes], [24, :hours], [Float::INFINITY, :days]].map{ |count, name|
if secs > 0
secs, n = secs.divmod(count)

"#{n.to_i} #{name}" unless n.to_i==0
end
}.compact.reverse.join(' ')
end

p humanize 1234
#=>"20 minutes 34 seconds"
p humanize 12345
#=>"3 hours 25 minutes 45 seconds"
p humanize 123456
#=>"1 days 10 hours 17 minutes 36 seconds"
p humanize(Time.now - Time.local(2010,11,5))
#=>"4 days 18 hours 24 minutes 7 seconds"

哦,请注意您的代码:

(self.created_at..self.updated_at).count

真正获得差异的糟糕方法。简单地使用:

self.updated_at - self.created_at

关于ruby-on-rails - 如何使用 ruby​​ on rails 生成人类可读的时间范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4136248/

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