计算连续天数的最佳方法
在我的应用程序中,用户有很多手势。计算用户随后做了多少天手势的好方法是什么?
现在我正在这样做,如下所示,它按照我想要的方式工作。但显然它无法扩展。
class User < ActiveRecord::Base
# ...
def calculate_current_streak
return 0 unless yesterday = gestures.done_on_day(Date.today-1)
i = 0
while gesture = self.gestures.done_on_day(Date.today - (i+1).days).first
i += 1
end
i += 1 if gestures.done_on_day(Date.today).first
i
end
end
谢谢!对于那些也可以只跟踪工作日的人来说,这是特别的一点:)
In my app a User has_many Gestures. What is a good way to calculate how many subsequent days the User has done Gestures?
Right now I'm doing it like below, and it works as I want it to. But clearly it doesn't scale.
class User < ActiveRecord::Base
# ...
def calculate_current_streak
return 0 unless yesterday = gestures.done_on_day(Date.today-1)
i = 0
while gesture = self.gestures.done_on_day(Date.today - (i+1).days).first
i += 1
end
i += 1 if gestures.done_on_day(Date.today).first
i
end
end
Thanks! Special points to the one who can work in a way to only track business days too :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这样想:
条纹的长度等于自用户根本没有使用手势的最后一个(工作日)以来经过的(工作日)天数,对吗?
因此,解决方案归结为计算用户最近没有做出手势的一天。
为了最轻松地做到这一点,许多数据库管理员使用了一个技巧:他们创建包含所有日期的数据库表(例如,从 2000 年到 2100 年的所有日期)。该表只需包含日期字段,但您可以添加布尔字段来标记非工作日,例如周末和节假日。这样的表在很多查询中非常方便,而且您只需创建并填充它一次。 (这里有一篇关于此类表的更详细的文章,是为 MS SQL 编写的,但无论如何都很有洞察力。)
有了这个表(我们称之为
日期
),您可以使用类似(伪 SQL)的东西来计算你的预记录日期:Think about it this way:
The length of the streak is equivalent to the number of (business) days passed since the last (business) day the user didn't use gestures at all, right?
So the solution boils down to calculating most recent day that the user didn't make a gesture.
In order to do this most easily, there's a trick that lots of DB admins use: they create DB table with all dates (say, all the dates from year 2000 to year 2100). The table needs to have only date field, but you can throw in a Boolean field to mark non-working days, such as weekends and holidays. Such table can be handy in lots of queries, and you only have to create and fill it once. (Here's a more detailed article on such tables, written for MS SQL, but insightful anyway.)
Having this table (let's call it
dates
), you can calculate your pre-streak date using something like (pseudo-SQL):