【问题标题】:Ruby Time and range inclusive/exclusiveRuby 时间和范围包括/不包括
【发布时间】:2014-07-24 10:06:46
【问题描述】:

现在我有一个辅助方法,它查看一个相对时间范围来确定你目前在吃什么。

def calculate_meal(time)

# Evening snack from midnight to 2:00am
# Morning Snack from 2:00:01am to 6:00am
# Breakfast 6:00:01am to 11:00 am
# Lunch 11:00:01am to 4:00pm
# Dinner  4:00:01 pm to 10:00pm
# Evening Snack 10:00:01pm to midnight
millisecond = 1
second = 1000
minute = 60*second
hour = 60*minute

if time.is_a? Hash

  time_hour     = time[:hour]
  time_minutes  = time[:minute]
  #time_sec      = time.sec
  #time_millisec = time.strftime("%L").to_i
  total_time = ((time_hour*60+time_minutes)*60)*second

elsif [ActiveSupport::TimeWithZone,Time].include? time.class

  time_hour     = time.hour
  time_minutes  = time.min
  time_sec      = time.sec
  time_millisec = time.strftime("%L").to_i
  total_time = ((time_hour*60+time_minutes)*60+time_sec)*second+time_millisec

end

puts total_time
case total_time
when 0..(hour*2)
  return :evening_snack
when ((hour*2+millisecond)..(6*hour))
  return :morning_snack
when ((6*hour+millisecond)..(11*hour))
  return :breakfast
when ((11*hour+millisecond)..(16*hour))
  return :lunch
when ((16*hour+millisecond)..(22*hour))
  return :dinner
when ((22*hour+millisecond)..(24*hour))
  return :evening_snack
end
end

我目前正在将范围分解为毫秒,但是有没有更好的方法来使用包含/排除范围来处理 Ruby 中的时间,以便涵盖所有时间和案例,而不是像现在这样有漏洞?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 time activesupport


    【解决方案1】:

    您可以使用... 排除终点但包含起点。所以大致如下:

    def calculate_interval(point)
      case point
      when 0...10
        "first"
      when 10...20
        "second"
      else
        "third"
      end
    end
    
    calculate_interval(0)  # => "first"
    calculate_interval(5)  # => "first"
    calculate_interval(10) # => "second"
    calculate_interval(20) # => "third"
    

    在您的特定情况下,您应该能够执行以下操作:

    case total_time
    when 0...(hour*2)
      return :evening_snack
    when ((hour*2)...(6*hour))
      return :morning_snack
    when ((6*hour)...(11*hour))
      return :breakfast
    when ((11*hour)...(16*hour))
      return :lunch
    when ((16*hour)...(22*hour))
      return :dinner
    when ((22*hour)..(24*hour)) # inclusive range depending on how you want to handle midnight
      return :evening_snack
    end
    end
    

    只需将.. 替换为... 即可满足您的需求。

    顺便说一句,如果您可以访问ActiveSupport::Time,您应该可以访问seconds_since_midnight 实例方法,该方法返回时间对象午夜以来的秒数。这将大大简化您的初始计算。

    例如,

    Time.now.seconds_since_midnight # => 67595.181868
    

    【讨论】:

    • seconds_since_midnight 函数如何考虑时间对象的时区偏移量很有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-09
    • 2010-09-09
    • 2018-07-10
    相关资源
    最近更新 更多