【问题标题】:How to count a method within a method如何计算方法中的方法
【发布时间】:2015-07-30 15:27:00
【问题描述】:

如果我们创建一个名为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)。

【问题讨论】:

    标签: ruby-on-rails ruby methods model integer


    【解决方案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】:

      执行此操作的基本方法:使 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-31
        • 2017-11-05
        • 2019-03-25
        • 2021-08-03
        相关资源
        最近更新 更多