如何计算方法中的方法
How to count a method within a method
如果我们创建一个名为 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)。
一个基本的方法:让current_level采用今天的值作为默认参数。之后,在 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
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
如果我们创建一个名为 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)。
一个基本的方法:让current_level采用今天的值作为默认参数。之后,在 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
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