如果我们创建一个名为days_left_in_current_level
的新方法,我们需要在那里放一些,以便我们可以计算current_level
中剩余的天数?
habit.rb
def current_level
return 0 unless date_started
def committed_wdays
committed.map do |day|
Date::ABBR_DAYNAMES.index(day.titleize)
end
end
def n_days
((date_started.to_date)..Date.today).count do |date|
committed_wdays.include? date.wday
end - self.real_missed_days
end
case n_days # 1 - 6 represent the different levels
when 0..9
1
when 10..24
2
when 25..44
3
when 45..69
4
when 70..99
5
else
6
end
end
如果您需要进一步的说明或代码(请参阅 Gist ),请与我们联系。
答案 0 :(得分:1)
执行此操作的基本方法:使current_level采用具有today的值的默认参数。之后,在days_left_in_current_level中,我只会增加一天,直到级别更改并计算迭代次数。
请记住,这几乎是伪代码,并且实际上没有尝试过运行它。还应该有更有效的方法来做到这一点。
def current_level(current_date = Date.today)
...snip...
((date_started.to_date)..current_date ).count do |date|
...snip...
end
def days_left_in_current_level
my_level = current_level
days_left = 0
next_level = current_level(Date.today + days_left + 1)
while next_level == my_level
days_left +=1
next_level = current_level(Date.today + days_left + 1)
end
end
答案 1 :(得分:1)
def days_left_in_current_level
def n_days
((date_started.to_date)..Date.today).count do |date|
committed_wdays.include? date.wday
end - self.real_missed_days
end
case n_days
when 0..9
10-n_days
when 10..24
25-n_days
when 25..44
45-n_days
when 45..69
70-n_days
when 70..99
100-n_days
else
0 # No end
end
end