ruby-on-rails - 使用 Ruby/Rails 在当前周期中寻找容量

标签 ruby-on-rails ruby

我有一个应用程序可以跟踪每个周期的容量(其中一个周期是从激活开始的几个月)。例如:

  • 2015 年 1 月 29 日中午 12:00 - 2015 年 2 月 28 日中午 12:00(第 1 周期)
  • 2015 年 2 月 28 日中午 12:00 - 2015 年 3 月 29 日中午 12:00(周期 #2)
  • 2015 年 3 月 29 日中午 12:00 - 2015 年 4 月 29 日中午 12:00(周期 #3)
  • ...

被跟踪的信息是“激活”日期(即初始周期的开始)。有没有一种计算给定日期的周期(范围)的好方法?我当前的实现有效但看起来很浪费(必须循环到日期):

def period(activated, time)
  cycles = 0
  cycles = cycles.next while activated + cycles.next.months < time
  return (activated + cycles.months)..(activated + cycles.next.months)
end

最佳答案

到 Rails,1.month is 30.days ,所以实际上,只需一点数学,您就可以在没有所有迭代的情况下做到这一点:

def period(activated, time)
  days = (time - activated).to_i
  cycle_idx = days / 30
  cycle_start = activated + cycle_idx * 30
  cycle_start..(cycle_start + 30)
end

让我分解一下:

activated = DateTime.parse('Jan 29, 2015 12:00PM') # => #<DateTime: 2015-01-29T12:00:00+00:00 ...>
time = DateTime.parse('Apr 15, 2015 6:00PM')       # => #<DateTime: 2015-04-30T12:00:00+00:00 ...>

# Get the number of days between `activated` and `time`.
days = (time - activated).to_i # => (305/4).to_i => 76

# Divide by 30 to get the cycle number (0-based).
cycle_idx = days / 30 # => 2

# Multiply the cycle number by 30 and add it to `activated` to get
# the beginning of the cycle.
cycle_start = activated + cycle_idx * 30 # => #<DateTime: 2015-03-30T12:00:00+00:00 ...>

# Add 30 more to get the end of the cycle.
cycle_start..(cycle_start + 30)
# => #<DateTime: 2015-03-30T12:00:00+00:00 ...>
#    ..#<DateTime: 2015-04-29T12:00:00+00:00 ...>

您会像我一样注意到,第三个周期从 3 月 30 日开始,而不是 3 月 29 日,这与您的示例不同。据我所知,这与您使用代码得到的结果相同,因为 2015 年 3 月 30 日是 2015 年 2 月 28 日之后的 30 天。

关于ruby-on-rails - 使用 Ruby/Rails 在当前周期中寻找容量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34324894/

相关文章:

ruby - 为什么我不能在 Ruby 中实例化 Integer 类?

ruby-on-rails - 在 Rails 项目中不断自动加载的问题(偶尔工作)

ruby - 告诉 sorbet Sequel 模型的继承层次结构

ruby-on-rails - 提交按钮文本来自哪里(Ruby on rails)?

ruby-on-rails - 命名空间内的 Rails 4 路由

javascript - 访问 Rails 资源时忽略 URL 中的范围区域设置

ruby-on-rails - 表单提交后设计覆盖重定向

ruby - 如何在 Windows 上的 Ruby 中保留行尾?

javascript - ruby 中的递归正则表达式