问题
If we create a new method called days_left_in_current_level
, what would we need to put in there so that we can count how many days are left in the 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
Please let me know if you need further explanation or code (here's the Gist of it).
回答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
回答2:
a basic way of doing this: make current_level take a default parameter with the value of today. After that, in the days_left_in_current_level i would just increase the day until the level changes and count the iterations.
keep in mind that this is almost pseudocode and haven't actually tried running it. there also should be more efficient ways of doing this.
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
来源:https://stackoverflow.com/questions/30314826/how-to-count-a-method-within-a-method