现在我有一个辅助方法,查看相对时间范围,以确定您目前正在吃什么餐。
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时间的包容性/独占范围,以便涵盖所有时间和案例,而不是像现在那样有漏洞?< / p>
答案 0 :(得分:2)
您可以使用...
排除结束点但包含起点。所以有些东西:
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