How to count a method within a method

狂风中的少年 提交于 2020-01-06 19:30:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!