How to count a method within a method

If we create a new method called days_left_in_current_level

what will we need to add there so we can calculate how many days are left in 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 a Gist of that).

0


source to share


2 answers


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

      



+1


source


the basic way to do this is: make current_level accept the default with today's value. After that, in days_left_in_current_level, I would just lengthen the day until the level changes and counts the iterations.

remember that this is almost pseudocode and didn't actually try to run it. there must also be better ways to do 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

      

+1


source







All Articles