【发布时间】:2014-04-02 08:06:26
【问题描述】:
我有这个代码:
@counter = 719
@period_hash = {
:sunset => 360,
:day => 720,
:dawn => 1200,
}
@period = :nothing
def init_period
periods = @period_hash.keys
@period_hash.each_with_index do |(__, number), index|
if @counter < number
@period = periods[index - 1]
break
end
end
if @period == :nothing
@period = periods[-1]
end
end
init_period
p @period
我有一个@counter,它的值在 0 到 1440 之间。 然后我有一个内容可变的哈希。内容将始终是符号 => 整数 整数值也将是 0 到 1440 之间的数字,并且所有数字在 哈希。哈希将被排序,因此最小的数字将是第一个和最大的数字 将是最后一个。
然后我有一个方法(init_period),它将返回与@counter 变量对应的键。 这些是@counter 的间隔和返回的符号:
0 .. 359 => :dawn
360 .. 719 => :sunset
720 .. 1199 => :day
1200 .. 1440 => :dawn
一切正常,但我想知道是否还有其他更好的方法可以做到这一点。
【问题讨论】: