【问题标题】:Use Hash Values like an Interval像间隔一样使用哈希值
【发布时间】: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

一切正常,但我想知道是否还有其他更好的方法可以做到这一点。

【问题讨论】:

    标签: ruby hashmap


    【解决方案1】:

    您可以使用以下代码实现将哈希转换为不同的结构。这不是很清楚,因为您使用的是 @period_hash 之外的信息(例如全局范围边界和必须重用最后一个值的事实)。

    hash = @period_hash.
      keys.
      unshift(@period_hash.keys.last).   # reuse last key from hash
      zip(                               # zip keys with ranges
        [0, *@period_hash.values, 1440]. # add 0 and 1440 as boundaries
        each_cons(2)                     # convert array to consecutive pairs enum
      ).each_with_object({}) {|(key, (from, to)), hash|
        hash[from...to] = key            # build actual hash
      }
    

    在这个结构上,你可以调用代码来检测你的月经:

    hash.detect {|a,b| a.include?(719) }
    

    您最终会得到非常不可读的代码。如果您的经期不会经常变化,您可以选择可读性很强的代码:

    def init_period(counter)
      case counter
      when 0...360     then :dawn
      when 360...720   then :sunset
      when 720...1200  then :day
      when 1200...1440 then :dawn
      end
    end
    

    这样周期边界不取自外部结构,但代码清晰明了。

    【讨论】:

    • 谢谢,我的第一个解决方案是使用案例,但后来我意识到,我编写了一个脚本供其他人(还有一些没有编程知识的人)使用,我想让它更加动态。我的脚本的用户可以配置散列并添加任意数量的项目,只要他们遵守规则。在散列中添加一些内容会更容易,例如:night => 1300,然后在代码下方某处的 case 语句中添加一个新的“when”。
    • 另一方面,范围可以用在 case 语句中。应该使用什么结构高度取决于实际用例。(来自 samuil 的评论,哈哈)。您使用范围和 case 语句的答案完全没用,因为 OP 明确指出哈希具有“可变内容”。您不能更改在 case 语句中硬编码的值。我会回复你的话:应该使用什么结构高度取决于实际用例。您的答案的第一部分有效,但很难看。
    猜你喜欢
    • 2017-11-11
    • 2020-11-01
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2013-07-21
    • 1970-01-01
    相关资源
    最近更新 更多